optimal vitural function
This commit is contained in:
@@ -35,10 +35,9 @@ Thư viện này được thiết kế để:
|
||||
- Quản lý nhiều nguồn dữ liệu với tên riêng biệt
|
||||
- **Quản lý odometry**: `addOdometry()` - cập nhật thông tin vị trí robot
|
||||
- **Navigation commands**:
|
||||
- `moveTo()` - di chuyển đến một điểm đích
|
||||
- `dockTo()` - docking đến marker (ví dụ: trạm sạc)
|
||||
- `moveStraightTo()` - di chuyển thẳng đến đích
|
||||
- `rotateTo()` - quay tại chỗ đến hướng mong muốn
|
||||
- `moveTo(goal, …)` - di chuyển đến một điểm đích
|
||||
- `moveTo(order, goal, …)` - một order VDA5050, được cắt thành từng chặng
|
||||
- `executeInstantActions(actions)` - một message `instantActions` của VDA5050 (0..n action)
|
||||
- **Điều khiển motion**:
|
||||
- `pause()` - tạm dừng di chuyển
|
||||
- `resume()` - tiếp tục di chuyển
|
||||
@@ -50,6 +49,21 @@ Thư viện này được thiết kế để:
|
||||
- `getFeedback()` - lấy feedback về trạng thái navigation
|
||||
- `getGlobalData()`, `getLocalData()` - lấy dữ liệu từ planner
|
||||
|
||||
**Bốn entry point đã bị gỡ khỏi interface**
|
||||
|
||||
`dockTo()` (hai overload), `moveStraightTo()` và `rotateTo()` không còn tồn tại. Chúng đẩy goal
|
||||
thẳng vào lõi navigation, bỏ qua mission layer, nên một goal đến giữa chừng lặng lẽ thay thế chặng
|
||||
mà hàng đợi mission đang chạy — rồi hàng đợi vẫn giao chặng kế tiếp của một tuyến robot đã rời khỏi.
|
||||
|
||||
Bốn kiểu chuyển động đó **không mất**: chúng là thuộc tính của từng chặng trong order
|
||||
(`profile: position | docking | go_straight | rotate`, cộng `marker` cho docking), nên đi cùng đường
|
||||
với mọi chặng khác — cùng mission id, cùng vòng đời, cùng đường cancel.
|
||||
|
||||
Ai còn gọi bốn hàm này: `nav_c_api` đã gỡ năm export tương ứng, `nav_c_api_2` gỡ
|
||||
`navigation_dock_to_order_v2`, OPC-UA gỡ ba method node `DockToNode` / `RotateTo` / `MoveStraight`.
|
||||
Binding .NET nào còn khai chúng sẽ hỏng lúc **chạy** (`EntryPointNotFoundException`), không phải lúc
|
||||
biên dịch.
|
||||
|
||||
**Đặc điểm:**
|
||||
|
||||
- Tất cả các phương thức đều là pure virtual, đảm bảo implementation đầy đủ
|
||||
@@ -149,7 +163,7 @@ Các hàm tiện ích hỗ trợ các thao tác phổ biến.
|
||||
|
||||
Các ứng dụng sử dụng navigation system:
|
||||
|
||||
- Gọi các phương thức `moveTo()`, `dockTo()`, `rotateTo()` để điều khiển robot
|
||||
- Gọi `moveTo()` hoặc `executeInstantActions()` để điều khiển robot
|
||||
- Theo dõi `NavFeedback` để biết trạng thái navigation
|
||||
- Sử dụng `getRobotPose()` để lấy vị trí hiện tại
|
||||
- Quản lý dữ liệu cảm biến thông qua các phương thức add/remove
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_msgs/PointCloud.h>
|
||||
#include <robot_sensor_msgs/PointCloud2.h>
|
||||
#include <robot_protocol_msgs/Action.h>
|
||||
#include <robot_protocol_msgs/Order.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
|
||||
@@ -409,49 +410,54 @@ namespace robot
|
||||
double yaw_goal_tolerance = 0.0) = 0;
|
||||
|
||||
/**
|
||||
* @brief Send a docking goal to a predefined marker (e.g. charger).
|
||||
* @param maker Marker name or ID.
|
||||
* @param goal Target pose for docking.
|
||||
* @param xy_goal_tolerance Acceptable XY error (meters).
|
||||
* @param yaw_goal_tolerance Acceptable heading error (radians).
|
||||
* @return True if docking command succeeded.
|
||||
* Docking, go-straight and rotate are no longer entry points of this contract.
|
||||
*
|
||||
* They used to exist as `dockTo` (two overloads), `moveStraightTo` and `rotateTo`, each
|
||||
* pushing a goal straight into the navigation core and bypassing the mission layer. That
|
||||
* bypass had no defined preemption semantics: a goal arriving through one of them silently
|
||||
* replaced whatever leg the mission queue was running, and the queue kept handing out the
|
||||
* next leg of a route the robot had already left.
|
||||
*
|
||||
* The motion profiles themselves are unchanged and still reachable — an order carries them
|
||||
* per leg (`profile: docking | go_straight | rotate`, plus `marker` for docking), so they
|
||||
* now travel the same path as every other leg: one mission id, one lifecycle, one cancel.
|
||||
*/
|
||||
virtual bool dockTo(const std::string &maker,
|
||||
const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) = 0;
|
||||
|
||||
/**
|
||||
* @brief Send a docking goal to a predefined marker (e.g. charger).
|
||||
* @param msg Order message.
|
||||
* @param goal Target pose for docking.
|
||||
* @param xy_goal_tolerance Acceptable XY error (meters).
|
||||
* @param yaw_goal_tolerance Acceptable heading error (radians).
|
||||
* @return True if docking command succeeded.
|
||||
* @brief Execute one VDA5050 `instantActions` message — a list of actions sent outside any order.
|
||||
*
|
||||
* This is the one entry point that takes bare actions. It exists because the four
|
||||
* removed above did not: it does not push anything into the core directly. The actions
|
||||
* are handed to the mission layer, which expands each against the same compound-action
|
||||
* table that node actions use and queues the resulting legs, so an instantAction gets
|
||||
* the same mission id, lifecycle and cancel path as any other work.
|
||||
*
|
||||
* The whole message goes down as ONE batch, in the order given. Submitting the actions
|
||||
* one at a time would break as soon as a message carried two of them: the second `HARD`
|
||||
* action preempts and wipes the legs of the first, so two commands sent together would
|
||||
* eat each other.
|
||||
*
|
||||
* Execution stops at the first leg that fails, and the rest of the message is dropped
|
||||
* with it (`clear_queue_on_failure`). The caller therefore reports one outcome for the
|
||||
* message, not one per action.
|
||||
*
|
||||
* `blockingType` decides how the batch meets a running order: any `HARD` action makes
|
||||
* the whole message preempt it; otherwise it queues behind it. `NONE` asks for
|
||||
* execution in parallel with driving, which this runtime cannot do — it is queued
|
||||
* instead, and the narrowing is logged.
|
||||
*
|
||||
* Lifecycle instantActions — `cancelOrder`, `startPause`, `stopPause` — must NOT come
|
||||
* through here. They steer the queue rather than being work in it; the host calls
|
||||
* @ref cancel, @ref pause and @ref resume for those.
|
||||
*
|
||||
* @param actions The actions of one `instantActions` message, in the order received.
|
||||
* Must not be empty; every action needs `actionType` and `actionId`.
|
||||
* @return True if the message was accepted. False means it was rejected outright — empty
|
||||
* list, missing identity, or the mission layer is not running — and the caller
|
||||
* must report failure rather than wait for a result that will not come.
|
||||
*/
|
||||
virtual bool dockTo(const robot_protocol_msgs::Order &msg,
|
||||
const std::string &marker,
|
||||
const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) = 0;
|
||||
|
||||
/**
|
||||
* @brief Move straight toward the target position (X-axis).
|
||||
* @param goal Target pose.
|
||||
* @param xy_goal_tolerance Acceptable positional error (meters).
|
||||
* @return True if command issued successfully.
|
||||
*/
|
||||
virtual bool moveStraightTo(const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0) = 0;
|
||||
|
||||
/**
|
||||
* @brief Rotate in place to align with target orientation.
|
||||
* @param goal Pose containing desired heading (only Z-axis used).
|
||||
* @param yaw_goal_tolerance Acceptable angular error (radians).
|
||||
* @return True if rotation command was sent successfully.
|
||||
*/
|
||||
virtual bool rotateTo(const robot_geometry_msgs::PoseStamped &goal,
|
||||
double yaw_goal_tolerance = 0.0) = 0;
|
||||
virtual bool executeInstantActions(
|
||||
const std::vector<robot_protocol_msgs::Action> &actions) = 0;
|
||||
|
||||
/**
|
||||
* @brief Pause the robot's movement (e.g. during obstacle avoidance).
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
# Move Base - Dual Build System Support
|
||||
|
||||
Package `move_base` có thể được build bằng cả **Catkin** và **Standalone CMake**.
|
||||
|
||||
## Cách Build
|
||||
|
||||
### 1. Build với Catkin (ROS Workspace)
|
||||
|
||||
**⚠️ QUAN TRỌNG**: Thư mục gốc của project (`pnkx_robot_nav_core`) có `CMakeLists.txt` ở root,
|
||||
nên **KHÔNG THỂ** chạy `catkin_make` trực tiếp trong thư mục đó. Catkin workspace không được
|
||||
phép có `CMakeLists.txt` ở root.
|
||||
|
||||
**Giải pháp**: Tạo một catkin workspace riêng và link packages vào đó.
|
||||
|
||||
#### Cách 1: Sử dụng script tự động (Khuyến nghị)
|
||||
|
||||
```bash
|
||||
# Chạy script setup từ thư mục gốc của project
|
||||
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core
|
||||
./setup_catkin_workspace.sh
|
||||
|
||||
# Script sẽ tạo workspace và link các packages có package.xml
|
||||
# Sau đó build:
|
||||
cd ../pnkx_nav_catkin_ws
|
||||
catkin_make
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
#### Cách 2: Tạo workspace thủ công
|
||||
|
||||
```bash
|
||||
# Tạo catkin workspace
|
||||
mkdir -p ~/pnkx_nav_catkin_ws/src
|
||||
cd ~/pnkx_nav_catkin_ws/src
|
||||
|
||||
# Link package move_base vào workspace
|
||||
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Navigations/Packages/move_base move_base
|
||||
|
||||
# Link các dependencies cần thiết (nếu có package.xml)
|
||||
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Libraries/tf3 tf3
|
||||
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Libraries/nav_2d_utils nav_2d_utils
|
||||
|
||||
# Build với catkin
|
||||
cd ~/pnkx_nav_catkin_ws
|
||||
catkin_make
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
**Lưu ý**: Khi build với catkin, package sẽ tự động detect và sử dụng:
|
||||
- `catkin_package()` để export dependencies
|
||||
- Catkin installation paths
|
||||
- ROS message dependencies
|
||||
|
||||
### 2. Build với Standalone CMake
|
||||
|
||||
```bash
|
||||
cd /path/to/move_base
|
||||
mkdir -p build
|
||||
cd build
|
||||
cmake ..
|
||||
make
|
||||
```
|
||||
|
||||
**Lưu ý**: Khi build standalone, bạn cần đảm bảo:
|
||||
- Tất cả dependencies đã được build trước
|
||||
- CMake có thể tìm thấy các internal packages (move_base_core, robot_nav_core, etc.)
|
||||
- ROS packages (nếu cần) được cài đặt và có trong CMAKE_PREFIX_PATH
|
||||
|
||||
## Cách CMakeLists.txt Detect Build Mode
|
||||
|
||||
CMakeLists.txt tự động detect build mode bằng cách kiểm tra:
|
||||
- `CATKIN_DEVEL_PREFIX` - biến môi trường của catkin
|
||||
- `CATKIN_TOPLEVEL` - biến môi trường của catkin
|
||||
|
||||
Nếu một trong hai biến này được định nghĩa, package sẽ build ở **Catkin mode**.
|
||||
Ngược lại, sẽ build ở **Standalone CMake mode**.
|
||||
|
||||
## Dependencies
|
||||
|
||||
### ROS Packages (khi build với Catkin):
|
||||
- roscpp, rospy
|
||||
- robot_std_msgs, geometry_msgs, robot_nav_msgs
|
||||
- tf2, tf2_ros
|
||||
- actionlib, dynamic_reconfigure
|
||||
|
||||
### Internal Packages (cần build trước):
|
||||
- move_base_core
|
||||
- robot_nav_core
|
||||
- robot_costmap_2d
|
||||
- xmlrpcpp
|
||||
- node_handle
|
||||
- robot_tf3_sensor_msgs
|
||||
- robot_tf3_geometry_msgs
|
||||
|
||||
### System Libraries:
|
||||
- Boost
|
||||
- yaml-cpp
|
||||
- pthread, dl
|
||||
|
||||
## Kiểm tra Build Mode
|
||||
|
||||
Khi chạy `cmake`, bạn sẽ thấy message:
|
||||
```
|
||||
Building move_base with Catkin
|
||||
```
|
||||
hoặc
|
||||
```
|
||||
Building move_base with Standalone CMake
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Lỗi: "catkin_make must be invoked in the root of workspace"
|
||||
**Nguyên nhân**: Thư mục hiện tại có `CMakeLists.txt` ở root, catkin không cho phép điều này.
|
||||
|
||||
**Giải pháp**:
|
||||
- Tạo catkin workspace riêng (xem hướng dẫn ở trên)
|
||||
- Hoặc đổi tên/ẩn `CMakeLists.txt` ở root khi build với catkin (không khuyến nghị)
|
||||
|
||||
### Lỗi: "Cannot find package X"
|
||||
- **Với Catkin**:
|
||||
- Đảm bảo package X đã được build trong cùng workspace
|
||||
- Đảm bảo package X có `package.xml` và được link vào `src/` của workspace
|
||||
- Kiểm tra dependencies trong `package.xml`
|
||||
- **Với Standalone**:
|
||||
- Đảm bảo package X đã được build và cài đặt
|
||||
- Thêm vào `CMAKE_PREFIX_PATH` nếu cần
|
||||
|
||||
### Lỗi: "catkin_package() not found"
|
||||
- Đảm bảo bạn đang build trong catkin workspace (không phải thư mục gốc có CMakeLists.txt)
|
||||
- Kiểm tra `CATKIN_DEVEL_PREFIX` có được set không
|
||||
- Source ROS setup: `source /opt/ros/noetic/setup.bash`
|
||||
|
||||
### Lỗi: "Cannot find ROS packages"
|
||||
- Cài đặt ROS Noetic: `sudo apt-get install ros-noetic-<package-name>`
|
||||
- Source ROS setup: `source /opt/ros/noetic/setup.bash`
|
||||
- Kiểm tra `ROS_PACKAGE_PATH` environment variable
|
||||
|
||||
### Lỗi: Internal packages không tìm thấy (move_base_core, robot_nav_core, etc.)
|
||||
- **Với Catkin**: Các internal packages cần có `package.xml` và được link vào workspace
|
||||
- **Với Standalone**: Đảm bảo các packages đã được build trước trong project chính
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(move_base VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building move_base with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building move_base with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS filesystem system)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(yaml-cpp REQUIRED)
|
||||
find_package(console_bridge REQUIRED)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
geometry_msgs
|
||||
robot_std_msgs
|
||||
move_base_core
|
||||
robot_nav_core
|
||||
robot_costmap_2d
|
||||
plugins
|
||||
tf3
|
||||
robot_tf3_sensor_msgs
|
||||
robot_tf3_geometry_msgs
|
||||
data_convert
|
||||
robot_nav_2d_utils
|
||||
robot_cpp
|
||||
robot_move_base_msgs
|
||||
laser_filter
|
||||
mission_adapters
|
||||
)
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
geometry_msgs
|
||||
robot_std_msgs
|
||||
move_base_core
|
||||
robot_nav_core
|
||||
robot_costmap_2d
|
||||
robot_tf3_sensor_msgs
|
||||
robot_tf3_geometry_msgs
|
||||
data_convert
|
||||
robot_nav_2d_utils
|
||||
robot_cpp
|
||||
robot_move_base_msgs
|
||||
mission_adapters
|
||||
)
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}
|
||||
CATKIN_DEPENDS mission_adapters geometry_msgs robot_std_msgs move_base_core robot_nav_core robot_costmap_2d robot_tf3_sensor_msgs robot_tf3_geometry_msgs data_convert robot_nav_2d_utils robot_cpp robot_move_base_msgs
|
||||
DEPENDS Boost yaml-cpp
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/move_base.cpp
|
||||
src/convert_data.cpp
|
||||
src/simple_action_server.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME}
|
||||
PUBLIC BUILD_WITH_ROS
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::filesystem Boost::system
|
||||
dl
|
||||
${TF3_LIBRARY}
|
||||
${console_bridge_LIBRARIES}
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
${TF3_LIBRARY}
|
||||
${console_bridge_LIBRARIES}
|
||||
PRIVATE
|
||||
Boost::filesystem Boost::system
|
||||
yaml-cpp
|
||||
dl
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Executable
|
||||
# ========================================================
|
||||
add_executable(${PROJECT_NAME}_main src/move_base_main.cpp)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
target_link_libraries(${PROJECT_NAME}_main PRIVATE
|
||||
${PROJECT_NAME}
|
||||
robot_cpp
|
||||
Boost::filesystem Boost::system
|
||||
dl
|
||||
${TF3_LIBRARY}
|
||||
${console_bridge_LIBRARIES}
|
||||
)
|
||||
else()
|
||||
target_link_libraries(${PROJECT_NAME}_main PRIVATE
|
||||
${PROJECT_NAME}
|
||||
robot_cpp
|
||||
Boost::filesystem Boost::system
|
||||
dl
|
||||
${TF3_LIBRARY}
|
||||
${console_bridge_LIBRARIES}
|
||||
)
|
||||
|
||||
# Configure RPATH to find libraries in devel space
|
||||
set_target_properties(${PROJECT_NAME}_main PROPERTIES
|
||||
BUILD_WITH_INSTALL_RPATH FALSE
|
||||
INSTALL_RPATH_USE_LINK_PATH TRUE
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_main
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_main
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: ${PROJECT_NAME}")
|
||||
message(STATUS "Executables: ${PROJECT_NAME}_main")
|
||||
message(STATUS "Dependencies: geometry_msgs, robot_std_msgs, move_base_core, robot_nav_core, robot_costmap_2d, robot_tf3_sensor_msgs, robot_tf3_geometry_msgs, data_convert, robot_nav_2d_utils, robot_cpp, robot_move_base_msgs, Boost, yaml-cpp")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
@@ -1,265 +0,0 @@
|
||||
# Hướng dẫn triển khai SimpleActionServer trong MoveBase
|
||||
|
||||
## Tổng quan
|
||||
|
||||
Tài liệu này hướng dẫn cách tích hợp `SimpleActionServer` vào class `MoveBase` hiện có.
|
||||
|
||||
## Bước 1: Thêm SimpleActionServer vào MoveBase class
|
||||
|
||||
### Trong `move_base.h`:
|
||||
|
||||
```cpp
|
||||
#include <move_base/simple_action_server.h>
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
class MoveBase : public robot::move_base_core::BaseNavigation
|
||||
{
|
||||
private:
|
||||
// Thêm member variable
|
||||
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> as_;
|
||||
|
||||
// Thêm method declaration
|
||||
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Bước 2: Khởi tạo trong constructor hoặc initialize()
|
||||
|
||||
### Trong `move_base.cpp` constructor hoặc `initialize()`:
|
||||
|
||||
```cpp
|
||||
void move_base::MoveBase::initialize(robot::TFListenerPtr tf)
|
||||
{
|
||||
// ... existing initialization code ...
|
||||
|
||||
// Khởi tạo action server
|
||||
as_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
|
||||
"move_base",
|
||||
std::bind(&MoveBase::executeCb, this, std::placeholders::_1),
|
||||
true // auto_start
|
||||
);
|
||||
|
||||
// Setup callbacks (optional)
|
||||
setupActionServerCallbacks();
|
||||
|
||||
robot::log_info("[MoveBase] Action server initialized");
|
||||
}
|
||||
```
|
||||
|
||||
## Bước 3: Setup callbacks (nếu cần publish messages)
|
||||
|
||||
```cpp
|
||||
void move_base::MoveBase::setupActionServerCallbacks()
|
||||
{
|
||||
if (!as_)
|
||||
return;
|
||||
|
||||
// Set callback để publish result
|
||||
// Customize để gửi qua hệ thống communication của bạn
|
||||
as_->setResultCallback([](const auto& result) {
|
||||
// TODO: Gửi result qua hệ thống communication của bạn
|
||||
// your_communication_system.send(result);
|
||||
robot::log_info("Result: status=%d", result->status.status);
|
||||
});
|
||||
|
||||
// Set callback để publish feedback
|
||||
as_->setFeedbackCallback([](const auto& feedback) {
|
||||
// TODO: Gửi feedback qua hệ thống communication của bạn
|
||||
// your_communication_system.send(feedback);
|
||||
});
|
||||
|
||||
// Set callback để publish status
|
||||
as_->setStatusCallback([](const auto& status) {
|
||||
// TODO: Gửi status qua hệ thống communication của bạn
|
||||
// your_communication_system.send(status);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Bước 4: Triển khai executeCb()
|
||||
|
||||
### Trong `move_base.cpp`:
|
||||
|
||||
```cpp
|
||||
void move_base::MoveBase::executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
|
||||
{
|
||||
robot::log_info("[MoveBase] Execute callback: x=%.2f, y=%.2f",
|
||||
goal->target_pose.pose.position.x,
|
||||
goal->target_pose.pose.position.y);
|
||||
|
||||
// Validate quaternion
|
||||
if (!isQuaternionValid(goal->target_pose.pose.orientation))
|
||||
{
|
||||
robot::log_error("[MoveBase] Invalid quaternion in goal");
|
||||
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Invalid quaternion in goal");
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert goal to global frame
|
||||
robot_geometry_msgs::PoseStamped target_pose = goalToGlobalFrame(goal->target_pose);
|
||||
|
||||
// Send goal to move_base
|
||||
bool success = moveTo(target_pose, 0.2, 0.2);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
robot::log_error("[MoveBase] Failed to send goal");
|
||||
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Failed to send goal to move_base");
|
||||
return;
|
||||
}
|
||||
|
||||
// Monitor execution
|
||||
robot::Rate rate(10.0);
|
||||
robot::Time last_feedback_time = robot::Time::now();
|
||||
|
||||
while (as_->isActive() && !as_->isPreemptRequested())
|
||||
{
|
||||
// Get feedback
|
||||
robot::move_base_core::NavFeedback* feedback = getFeedback();
|
||||
|
||||
if (feedback)
|
||||
{
|
||||
// Check if goal reached
|
||||
if (feedback->goal_checked &&
|
||||
feedback->navigation_state == robot::move_base_core::State::SUCCEEDED)
|
||||
{
|
||||
as_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal reached");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for errors
|
||||
if (feedback->navigation_state == robot::move_base_core::State::ABORTED)
|
||||
{
|
||||
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
feedback->feed_back_str);
|
||||
return;
|
||||
}
|
||||
|
||||
// Publish feedback periodically
|
||||
robot::Time now = robot::Time::now();
|
||||
if ((now - last_feedback_time).toSec() >= 0.5)
|
||||
{
|
||||
robot_move_base_msgs::MoveBaseFeedback fb;
|
||||
fb.base_position.x = feedback->current_pose.x;
|
||||
fb.base_position.y = feedback->current_pose.y;
|
||||
fb.base_position.theta = feedback->current_pose.theta;
|
||||
fb.base_position.header.stamp = robot::Time::now();
|
||||
fb.base_position.header.frame_id = global_frame_;
|
||||
|
||||
as_->publishFeedback(fb);
|
||||
last_feedback_time = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for preemption
|
||||
if (as_->isPreemptRequested())
|
||||
{
|
||||
cancel();
|
||||
as_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Preempted");
|
||||
return;
|
||||
}
|
||||
|
||||
rate.sleep();
|
||||
}
|
||||
|
||||
// Handle unexpected exit
|
||||
if (as_->isPreemptRequested())
|
||||
{
|
||||
cancel();
|
||||
as_->setPreempted(robot_move_base_msgs::MoveBaseResult(), "Preempted");
|
||||
}
|
||||
else
|
||||
{
|
||||
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Execution ended unexpectedly");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Bước 5: Xử lý goal và cancel messages từ bên ngoài
|
||||
|
||||
Nhận goal và cancel messages từ hệ thống communication của bạn:
|
||||
|
||||
```cpp
|
||||
// Trong callback nhận goal từ hệ thống communication của bạn
|
||||
void move_base::MoveBase::goalCallback(
|
||||
const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
|
||||
{
|
||||
if (as_)
|
||||
{
|
||||
as_->processGoal(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// Trong callback nhận cancel từ hệ thống communication của bạn
|
||||
void move_base::MoveBase::cancelCallback(
|
||||
const robot_actionlib_msgs::GoalIDConstPtr& msg)
|
||||
{
|
||||
if (as_)
|
||||
{
|
||||
as_->processCancel(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// Ví dụ: Đăng ký với hệ thống communication của bạn
|
||||
// your_communication_system.onGoal(
|
||||
// std::bind(&MoveBase::goalCallback, this, std::placeholders::_1));
|
||||
// your_communication_system.onCancel(
|
||||
// std::bind(&MoveBase::cancelCallback, this, std::placeholders::_1));
|
||||
```
|
||||
|
||||
## Bước 6: Cleanup trong destructor
|
||||
|
||||
```cpp
|
||||
move_base::MoveBase::~MoveBase()
|
||||
{
|
||||
// ... existing cleanup ...
|
||||
|
||||
// Stop action server
|
||||
if (as_)
|
||||
{
|
||||
as_->stop();
|
||||
as_.reset();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Ví dụ hoàn chỉnh
|
||||
|
||||
Xem các file trong thư mục `examples/`:
|
||||
- `simple_usage_example.cpp` - Ví dụ đơn giản nhất
|
||||
- `simple_action_server_example.cpp` - Ví dụ đầy đủ
|
||||
- `move_base_with_action_server_example.cpp` - Ví dụ tích hợp vào MoveBase
|
||||
|
||||
## Lưu ý
|
||||
|
||||
1. **Thread Safety**: `executeCb` chạy trong thread riêng, đảm bảo thread-safe khi truy cập các member variables
|
||||
2. **State Management**: Action server tự động quản lý state, không cần can thiệp thủ công
|
||||
3. **Feedback Rate**: Điều chỉnh rate publish feedback phù hợp (khuyến nghị 0.5-1.0 giây)
|
||||
4. **Error Handling**: Luôn kiểm tra và xử lý các trường hợp lỗi
|
||||
|
||||
## Testing
|
||||
|
||||
Để test action server:
|
||||
|
||||
```cpp
|
||||
// Tạo goal message
|
||||
robot_move_base_msgs::MoveBaseActionGoalPtr goal =
|
||||
boost::make_shared<robot_move_base_msgs::MoveBaseActionGoal>();
|
||||
goal->goal_id.id = "test_goal_1";
|
||||
goal->goal.target_pose.pose.position.x = 5.0;
|
||||
goal->goal.target_pose.pose.position.y = 3.0;
|
||||
|
||||
// Gửi goal
|
||||
move_base_ptr->getActionServer()->processGoal(goal);
|
||||
|
||||
// Kiểm tra status
|
||||
auto status = move_base_ptr->getActionServer()->getCurrentStatus();
|
||||
```
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
# SimpleActionServer - Hướng dẫn sử dụng
|
||||
|
||||
## Tổng quan
|
||||
|
||||
`SimpleActionServer` là một thư viện tương tự ROS actionlib::SimpleActionServer nhưng không phụ thuộc vào ROS. Nó cung cấp interface đơn giản để triển khai action server với các tính năng:
|
||||
|
||||
- Quản lý goal requests
|
||||
- Hỗ trợ preemption (hủy goal)
|
||||
- Publish feedback và result thông qua callbacks
|
||||
- Thread-safe và thread-safe state management
|
||||
- Tương thích với framework robot hiện có
|
||||
|
||||
## Cấu trúc Files
|
||||
|
||||
- `simple_action_server.h` - Header file với class declaration
|
||||
- `simple_action_server.cpp` - Implementation file với template code
|
||||
- `simple_action_server_example.cpp` - Ví dụ triển khai đầy đủ
|
||||
|
||||
## Ví dụ sử dụng cơ bản
|
||||
|
||||
### 1. Khởi tạo SimpleActionServer
|
||||
|
||||
```cpp
|
||||
#include <move_base/simple_action_server.h>
|
||||
|
||||
// Tạo action server với execute callback
|
||||
auto action_server = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
|
||||
"move_base",
|
||||
[this](const auto& goal) { this->executeCb(goal); },
|
||||
true // auto_start
|
||||
);
|
||||
```
|
||||
|
||||
### 2. Setup callbacks để publish messages
|
||||
|
||||
```cpp
|
||||
// Set callback để publish result
|
||||
action_server->setResultCallback([](const auto& result) {
|
||||
// Publish result message qua ROS hoặc hệ thống khác
|
||||
result_pub_.publish(*result);
|
||||
});
|
||||
|
||||
// Set callback để publish feedback
|
||||
action_server->setFeedbackCallback([](const auto& feedback) {
|
||||
// Publish feedback message
|
||||
feedback_pub_.publish(*feedback);
|
||||
});
|
||||
|
||||
// Set callback để publish status
|
||||
action_server->setStatusCallback([](const auto& status) {
|
||||
// Publish status message
|
||||
status_pub_.publish(*status);
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Xử lý goal messages từ bên ngoài
|
||||
|
||||
```cpp
|
||||
// Trong ROS subscriber callback hoặc nơi nhận goal
|
||||
void goalCallback(const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
|
||||
{
|
||||
action_server->processGoal(msg);
|
||||
}
|
||||
|
||||
// Trong cancel callback
|
||||
void cancelCallback(const robot_actionlib_msgs::GoalIDConstPtr& msg)
|
||||
{
|
||||
action_server->processCancel(msg);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Triển khai execute callback
|
||||
|
||||
```cpp
|
||||
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
|
||||
{
|
||||
robot::log_info("Received goal: x=%.2f, y=%.2f",
|
||||
goal->target_pose.pose.position.x,
|
||||
goal->target_pose.pose.position.y);
|
||||
|
||||
// Gửi goal đến move_base
|
||||
bool success = move_base_ptr_->moveTo(goal->target_pose, 0.2, 0.2);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Failed to send goal");
|
||||
return;
|
||||
}
|
||||
|
||||
// Monitor execution
|
||||
robot::Rate rate(10.0);
|
||||
while (action_server_->isActive() && !action_server_->isPreemptRequested())
|
||||
{
|
||||
// Kiểm tra trạng thái
|
||||
auto* feedback = move_base_ptr_->getFeedback();
|
||||
if (feedback->goal_checked &&
|
||||
feedback->navigation_state == robot::move_base_core::State::SUCCEEDED)
|
||||
{
|
||||
action_server_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal reached");
|
||||
return;
|
||||
}
|
||||
|
||||
// Publish feedback
|
||||
robot_move_base_msgs::MoveBaseFeedback fb;
|
||||
fb.base_position.x = feedback->current_pose.x;
|
||||
fb.base_position.y = feedback->current_pose.y;
|
||||
action_server_->publishFeedback(fb);
|
||||
|
||||
rate.sleep();
|
||||
}
|
||||
|
||||
// Xử lý preemption
|
||||
if (action_server_->isPreemptRequested())
|
||||
{
|
||||
move_base_ptr_->cancel();
|
||||
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Preempted");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tích hợp vào MoveBase
|
||||
|
||||
### Cách 1: Thêm vào MoveBase class
|
||||
|
||||
```cpp
|
||||
// Trong move_base.h
|
||||
#include <move_base/simple_action_server.h>
|
||||
|
||||
class MoveBase : public robot::move_base_core::BaseNavigation
|
||||
{
|
||||
private:
|
||||
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> as_;
|
||||
|
||||
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal);
|
||||
};
|
||||
```
|
||||
|
||||
```cpp
|
||||
// Trong move_base.cpp constructor
|
||||
MoveBase::MoveBase(robot::TFListenerPtr tf)
|
||||
{
|
||||
// ... existing initialization ...
|
||||
|
||||
// Create action server
|
||||
as_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
|
||||
"move_base",
|
||||
std::bind(&MoveBase::executeCb, this, std::placeholders::_1),
|
||||
true
|
||||
);
|
||||
|
||||
// Setup callbacks
|
||||
as_->setResultCallback([this](const auto& result) {
|
||||
// Publish result if needed
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Cách 2: Sử dụng trong wrapper class
|
||||
|
||||
Xem file `simple_action_server_example.cpp` để xem ví dụ đầy đủ.
|
||||
|
||||
## API Reference
|
||||
|
||||
### Constructor
|
||||
```cpp
|
||||
SimpleActionServer(const std::string& name,
|
||||
ExecuteCallback execute_callback,
|
||||
bool auto_start = true)
|
||||
```
|
||||
|
||||
### Main Methods
|
||||
- `void processGoal(const ActionGoalConstPtr& goal_msg)` - Xử lý goal message
|
||||
- `void processCancel(const GoalIDConstPtr& cancel_msg)` - Xử lý cancel message
|
||||
- `GoalConstPtr acceptNewGoal()` - Chấp nhận goal mới
|
||||
- `bool isNewGoalAvailable()` - Kiểm tra có goal mới
|
||||
- `bool isPreemptRequested()` - Kiểm tra preemption
|
||||
- `void setSucceeded(const Result&, const std::string&)` - Đặt thành công
|
||||
- `void setAborted(const Result&, const std::string&)` - Đặt lỗi
|
||||
- `void setPreempted(const Result&, const std::string&)` - Đặt preempted
|
||||
- `void publishFeedback(const Feedback&)` - Publish feedback
|
||||
|
||||
### Callback Setup
|
||||
- `void setGoalCallback(GoalCallback)` - Callback khi nhận goal
|
||||
- `void setCancelCallback(CancelCallback)` - Callback khi nhận cancel
|
||||
- `void setFeedbackCallback(FeedbackCallback)` - Callback để publish feedback
|
||||
- `void setResultCallback(ResultCallback)` - Callback để publish result
|
||||
- `void setStatusCallback(StatusCallback)` - Callback để publish status
|
||||
|
||||
## Lưu ý
|
||||
|
||||
1. **Thread Safety**: Tất cả các phương thức đều thread-safe
|
||||
2. **Callbacks**: Các callbacks được gọi trong context của thread tương ứng
|
||||
3. **State Management**: Action server tự động quản lý state machine
|
||||
4. **No ROS Dependency**: Không cần ROS, chỉ cần setup callbacks để publish messages
|
||||
|
||||
## Tích hợp với hệ thống communication khác
|
||||
|
||||
SimpleActionServer không phụ thuộc vào ROS. Bạn có thể tích hợp với bất kỳ hệ thống communication nào bằng cách setup callbacks:
|
||||
|
||||
```cpp
|
||||
// Setup callbacks để publish messages qua hệ thống của bạn
|
||||
action_server->setResultCallback([](const auto& result) {
|
||||
// Gửi result qua hệ thống communication của bạn
|
||||
// your_communication_system.send(result);
|
||||
});
|
||||
|
||||
action_server->setFeedbackCallback([](const auto& feedback) {
|
||||
// Gửi feedback qua hệ thống communication của bạn
|
||||
// your_communication_system.send(feedback);
|
||||
});
|
||||
|
||||
// Nhận goal messages từ hệ thống của bạn
|
||||
// your_communication_system.onGoal([&action_server](const auto& msg) {
|
||||
// action_server->processGoal(msg);
|
||||
// });
|
||||
```
|
||||
|
||||
@@ -1,343 +0,0 @@
|
||||
/**
|
||||
* @file simple_action_server_example.cpp
|
||||
* @brief Example implementation of SimpleActionServer for MoveBaseAction
|
||||
*
|
||||
* This example demonstrates how to use SimpleActionServer to implement
|
||||
* an action server without ROS dependency. It shows:
|
||||
* - How to initialize the action server
|
||||
* - How to set up callbacks for publishing messages
|
||||
* - How to handle goal execution
|
||||
* - How to publish feedback and results
|
||||
*/
|
||||
|
||||
#include <move_base/simple_action_server.h>
|
||||
#include <move_base/move_base.h>
|
||||
|
||||
// Message types
|
||||
#include <robot_move_base_msgs/MoveBaseActionGoal.h>
|
||||
#include <robot_move_base_msgs/MoveBaseActionResult.h>
|
||||
#include <robot_move_base_msgs/MoveBaseActionFeedback.h>
|
||||
#include <robot_actionlib_msgs/GoalID.h>
|
||||
#include <robot_actionlib_msgs/GoalStatusArray.h>
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
|
||||
/**
|
||||
* @class MoveBaseActionServerExample
|
||||
* @brief Example class demonstrating SimpleActionServer usage
|
||||
*/
|
||||
class MoveBaseActionServerExample
|
||||
{
|
||||
public:
|
||||
MoveBaseActionServerExample()
|
||||
: move_base_ptr_(nullptr)
|
||||
{
|
||||
// Initialize move_base (your existing navigation system)
|
||||
// move_base_ptr_ = std::make_shared<MoveBase>(tf_);
|
||||
|
||||
// Create SimpleActionServer with execute callback
|
||||
action_server_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
|
||||
"move_base",
|
||||
std::bind(&MoveBaseActionServerExample::executeCb, this, std::placeholders::_1),
|
||||
true // auto_start
|
||||
);
|
||||
|
||||
// Set up callbacks for publishing messages
|
||||
setupCallbacks();
|
||||
|
||||
robot::log_info("[MoveBaseActionServerExample] Initialized");
|
||||
}
|
||||
|
||||
~MoveBaseActionServerExample()
|
||||
{
|
||||
if (action_server_)
|
||||
{
|
||||
action_server_->stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Setup callbacks for SimpleActionServer
|
||||
* You can customize these callbacks to publish messages to your communication system
|
||||
*/
|
||||
void setupCallbacks()
|
||||
{
|
||||
if (!action_server_)
|
||||
return;
|
||||
|
||||
// Set callback for result publishing
|
||||
// Customize this to send result to your communication system
|
||||
action_server_->setResultCallback(
|
||||
[this](const robot_move_base_msgs::MoveBaseActionResultConstPtr& result)
|
||||
{
|
||||
// TODO: Publish result to your communication system (e.g., custom message bus, network, etc.)
|
||||
robot::log_info("[MoveBaseActionServerExample] Result: status=%d, text=%s",
|
||||
result->status.status, result->status.text.c_str());
|
||||
}
|
||||
);
|
||||
|
||||
// Set callback for feedback publishing
|
||||
// Customize this to send feedback to your communication system
|
||||
action_server_->setFeedbackCallback(
|
||||
[this](const robot_move_base_msgs::MoveBaseActionFeedbackConstPtr& feedback)
|
||||
{
|
||||
// TODO: Publish feedback to your communication system
|
||||
robot::log_debug("[MoveBaseActionServerExample] Published feedback");
|
||||
}
|
||||
);
|
||||
|
||||
// Set callback for status publishing
|
||||
// Customize this to send status to your communication system
|
||||
action_server_->setStatusCallback(
|
||||
[this](const robot_actionlib_msgs::GoalStatusArrayConstPtr& status)
|
||||
{
|
||||
// TODO: Publish status to your communication system
|
||||
}
|
||||
);
|
||||
|
||||
// Set callback for goal messages (optional - for logging)
|
||||
action_server_->setGoalCallback(
|
||||
[this](const robot_move_base_msgs::MoveBaseActionGoalConstPtr& goal)
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Goal callback: x=%.2f, y=%.2f",
|
||||
goal->goal.target_pose.pose.position.x,
|
||||
goal->goal.target_pose.pose.position.y);
|
||||
}
|
||||
);
|
||||
|
||||
// Set callback for cancel messages (optional - for logging)
|
||||
action_server_->setCancelCallback(
|
||||
[this](const robot_actionlib_msgs::GoalIDConstPtr& cancel)
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Cancel callback: id=%s", cancel->id.c_str());
|
||||
}
|
||||
);
|
||||
|
||||
// Set status publish rate (default is 10 Hz)
|
||||
action_server_->setStatusPublishRate(10.0);
|
||||
|
||||
robot::log_info("[MoveBaseActionServerExample] Callbacks setup complete");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Process goal message from external source
|
||||
* Call this when you receive a goal message from your communication system
|
||||
*/
|
||||
void processGoalMessage(const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
|
||||
{
|
||||
if (action_server_)
|
||||
{
|
||||
action_server_->processGoal(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Process cancel message from external source
|
||||
* Call this when you receive a cancel message from your communication system
|
||||
*/
|
||||
void processCancelMessage(const robot_actionlib_msgs::GoalIDConstPtr& msg)
|
||||
{
|
||||
if (action_server_)
|
||||
{
|
||||
action_server_->processCancel(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Execute callback - called when a new goal is received
|
||||
* This is the main function that processes the goal
|
||||
*/
|
||||
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Execute callback started");
|
||||
robot::log_info(" Goal: x=%.2f, y=%.2f, frame_id=%s",
|
||||
goal->target_pose.pose.position.x,
|
||||
goal->target_pose.pose.position.y,
|
||||
goal->target_pose.header.frame_id.c_str());
|
||||
|
||||
// Check if we have a valid move_base instance
|
||||
if (!move_base_ptr_)
|
||||
{
|
||||
robot::log_error("[MoveBaseActionServerExample] move_base_ptr_ is null, aborting goal");
|
||||
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"MoveBase not initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert goal to PoseStamped
|
||||
robot_geometry_msgs::PoseStamped target_pose = goal->target_pose;
|
||||
|
||||
// Send goal to move_base
|
||||
bool success = move_base_ptr_->moveTo(target_pose, 0.2, 0.2);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
robot::log_error("[MoveBaseActionServerExample] Failed to send goal to move_base");
|
||||
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Failed to send goal to move_base");
|
||||
return;
|
||||
}
|
||||
|
||||
// Monitor execution and publish feedback
|
||||
robot::Rate rate(10.0); // 10 Hz
|
||||
robot::Time start_time = robot::Time::now();
|
||||
robot::Time last_feedback_time = start_time;
|
||||
|
||||
while (action_server_->isActive() && !action_server_->isPreemptRequested())
|
||||
{
|
||||
// Check if goal is reached
|
||||
if (move_base_ptr_->getFeedback())
|
||||
{
|
||||
auto* feedback_ptr = move_base_ptr_->getFeedback();
|
||||
|
||||
if (feedback_ptr->goal_checked &&
|
||||
feedback_ptr->navigation_state == robot::move_base_core::State::SUCCEEDED)
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Goal reached!");
|
||||
action_server_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal reached successfully");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for errors
|
||||
if (feedback_ptr->navigation_state == robot::move_base_core::State::ABORTED)
|
||||
{
|
||||
robot::log_error("[MoveBaseActionServerExample] Navigation aborted: %s",
|
||||
feedback_ptr->feed_back_str.c_str());
|
||||
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
feedback_ptr->feed_back_str);
|
||||
return;
|
||||
}
|
||||
|
||||
// Publish feedback periodically (every 0.5 seconds)
|
||||
robot::Time now = robot::Time::now();
|
||||
if ((now - last_feedback_time).toSec() >= 0.5)
|
||||
{
|
||||
robot_move_base_msgs::MoveBaseFeedback feedback;
|
||||
feedback.base_position.x = feedback_ptr->current_pose.x;
|
||||
feedback.base_position.y = feedback_ptr->current_pose.y;
|
||||
feedback.base_position.theta = feedback_ptr->current_pose.theta;
|
||||
feedback.base_position.header.stamp = robot::Time::now();
|
||||
feedback.base_position.header.frame_id = "map";
|
||||
|
||||
action_server_->publishFeedback(feedback);
|
||||
last_feedback_time = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for preemption
|
||||
if (action_server_->isPreemptRequested())
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Goal preempted");
|
||||
move_base_ptr_->cancel();
|
||||
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal preempted by user");
|
||||
return;
|
||||
}
|
||||
|
||||
// Sleep
|
||||
rate.sleep();
|
||||
}
|
||||
|
||||
// If we exit the loop without success, check why
|
||||
if (action_server_->isPreemptRequested())
|
||||
{
|
||||
robot::log_info("[MoveBaseActionServerExample] Goal was preempted");
|
||||
move_base_ptr_->cancel();
|
||||
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal preempted");
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning("[MoveBaseActionServerExample] Goal execution ended unexpectedly");
|
||||
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
|
||||
"Goal execution ended unexpectedly");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the action server instance
|
||||
*/
|
||||
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> getActionServer()
|
||||
{
|
||||
return action_server_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set move_base instance
|
||||
*/
|
||||
void setMoveBase(robot::move_base_core::BaseNavigation::Ptr move_base)
|
||||
{
|
||||
move_base_ptr_ = move_base;
|
||||
}
|
||||
|
||||
private:
|
||||
// Action server
|
||||
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> action_server_;
|
||||
|
||||
// Move base instance
|
||||
robot::move_base_core::BaseNavigation::Ptr move_base_ptr_;
|
||||
};
|
||||
|
||||
} // namespace move_base
|
||||
|
||||
/**
|
||||
* @brief Example main function showing how to use MoveBaseActionServerExample
|
||||
*/
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Create example instance
|
||||
move_base::MoveBaseActionServerExample example;
|
||||
|
||||
// If you have a move_base instance, set it
|
||||
// example.setMoveBase(move_base_ptr);
|
||||
|
||||
robot::log_info("[Example] Action server is running. Waiting for goals...");
|
||||
|
||||
// Example: Create and send a goal message
|
||||
// In real usage, you would receive this from your communication system
|
||||
robot_move_base_msgs::MoveBaseActionGoalPtr goal_msg =
|
||||
boost::make_shared<robot_move_base_msgs::MoveBaseActionGoal>();
|
||||
goal_msg->header.stamp = robot::Time::now();
|
||||
goal_msg->header.frame_id = "map";
|
||||
goal_msg->goal_id.stamp = robot::Time::now();
|
||||
goal_msg->goal_id.id = "example_goal_1";
|
||||
goal_msg->goal.target_pose.header.stamp = robot::Time::now();
|
||||
goal_msg->goal.target_pose.header.frame_id = "map";
|
||||
goal_msg->goal.target_pose.pose.position.x = 5.0;
|
||||
goal_msg->goal.target_pose.pose.position.y = 3.0;
|
||||
goal_msg->goal.target_pose.pose.position.z = 0.0;
|
||||
goal_msg->goal.target_pose.pose.orientation.w = 1.0;
|
||||
|
||||
// Process the goal
|
||||
example.processGoalMessage(goal_msg);
|
||||
|
||||
// Your event loop here
|
||||
// while (your_system_running())
|
||||
// {
|
||||
// // Receive messages from your communication system
|
||||
// // Process goals and cancels
|
||||
// // example.processGoalMessage(goal_msg);
|
||||
// // example.processCancelMessage(cancel_msg);
|
||||
// }
|
||||
|
||||
// Keep running for a while
|
||||
robot::Time::sleep(robot::Duration(10.0));
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
robot::log_error("[Example] Exception: %s", e.what());
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
#ifndef MOVE_BASE_CONVERT_DATA_H
|
||||
#define MOVE_BASE_CONVERT_DATA_H
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
#include <robot_map_msgs/OccupancyGridUpdate.h>
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
class ConvertData
|
||||
{
|
||||
public:
|
||||
ConvertData(robot_costmap_2d::Costmap2DROBOT* costmap, std::string global_frame, bool always_send_full_costmap = false);
|
||||
~ConvertData();
|
||||
|
||||
/** @brief Update data for publication. */
|
||||
void updateCostmap(robot_nav_msgs::OccupancyGrid &grid, robot_map_msgs::OccupancyGridUpdate &update, bool &is_updated);
|
||||
|
||||
void updateFootprint(robot_geometry_msgs::PolygonStamped &footprint);
|
||||
|
||||
private:
|
||||
/** @brief Prepare grid_ message for publication. */
|
||||
void prepareGrid();
|
||||
|
||||
/** @brief Include the given bounds in the changed-rectangle. */
|
||||
void updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn);
|
||||
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_;
|
||||
std::string global_frame_;
|
||||
unsigned int x0_, xn_, y0_, yn_;
|
||||
double saved_origin_x_, saved_origin_y_;
|
||||
bool always_send_full_costmap_;
|
||||
robot_nav_msgs::OccupancyGrid grid_;
|
||||
static char* cost_translation_table_; ///< Translate from 0-255 values in costmap to -1 to 100 values in message.
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -1,717 +0,0 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Author: Kevin Lee
|
||||
*********************************************************************/
|
||||
#ifndef NAV_MOVE_BASE_ACTION_H_
|
||||
#define NAV_MOVE_BASE_ACTION_H_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <move_base/simple_action_server.h>
|
||||
|
||||
// interfaces headers
|
||||
#include <move_base_core/navigation.h>
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <robot_nav_core/base_local_planner.h>
|
||||
#include <robot_nav_core/recovery_behavior.h>
|
||||
#include <mission_adapters/mission_adapters.h>
|
||||
|
||||
// boost headers
|
||||
#include <boost/thread.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/thread/recursive_mutex.hpp>
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <robot_nav_msgs/GetPlan.h>
|
||||
#include <robot_protocol_msgs/Order.h>
|
||||
#include <robot_move_base_msgs/MoveBaseAction.h>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
template <class T>
|
||||
void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::string name,T& value)
|
||||
{
|
||||
if (!old_h.hasParam(name))
|
||||
return;
|
||||
|
||||
old_h.getParam(name, value);
|
||||
new_h.setParam(name, value);
|
||||
}
|
||||
|
||||
|
||||
// typedefs to help us out with the action server so that we don't hace to type so much
|
||||
typedef move_base::SimpleActionServer<robot_move_base_msgs::MoveBaseAction> MoveBaseActionServer;
|
||||
|
||||
enum MoveBaseState
|
||||
{
|
||||
PLANNING,
|
||||
CONTROLLING,
|
||||
CLEARING
|
||||
};
|
||||
|
||||
enum RecoveryTrigger
|
||||
{
|
||||
PLANNING_R,
|
||||
CONTROLLING_R,
|
||||
OSCILLATION_R
|
||||
};
|
||||
|
||||
struct MoveBaseConfig
|
||||
{
|
||||
std::string base_global_planner;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class MoveBase
|
||||
* @brief A class that uses the actionlib::ActionServer interface that moves the robot base to a goal location.
|
||||
*/
|
||||
class MoveBase : public robot::move_base_core::BaseNavigation
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the actions
|
||||
* @param tf A reference to a TransformListener
|
||||
*/
|
||||
MoveBase(robot::TFListenerPtr tf);
|
||||
|
||||
/**
|
||||
* @brief Default constructor for the actions
|
||||
*/
|
||||
MoveBase();
|
||||
|
||||
/**
|
||||
* @brief Initialize the navigation system.
|
||||
* @param tf Shared pointer to the TF listener or buffer.
|
||||
*/
|
||||
virtual void initialize(robot::TFListenerPtr tf) override;
|
||||
|
||||
/**
|
||||
* @brief Initialize the cost-to-occupancy lookup table for costmap conversion
|
||||
*/
|
||||
static void initializeCostToOccupancyLUT();
|
||||
|
||||
/**
|
||||
* @brief Set the robot's footprint (outline shape) in the global frame.
|
||||
* This can be used for planning or collision checking.
|
||||
*
|
||||
* @param fprt A vector of points representing the robot's footprint polygon.
|
||||
* The points should be ordered counter-clockwise.
|
||||
*/
|
||||
virtual void setRobotFootprint(const std::vector<robot_geometry_msgs::Point> &fprt) override;
|
||||
|
||||
/**
|
||||
* @brief Get the robot's footprint (outline shape) in the global frame.
|
||||
* @return A vector of points representing the robot's footprint polygon.
|
||||
*/
|
||||
virtual std::vector<robot_geometry_msgs::Point> getRobotFootprint() override;
|
||||
|
||||
/**
|
||||
* @brief Add a static map to the navigation system.
|
||||
* @param map_name The name of the map.
|
||||
* @param map The map to add.
|
||||
*/
|
||||
virtual void addStaticMap(const std::string &map_name, robot_nav_msgs::OccupancyGrid map) override;
|
||||
|
||||
/**
|
||||
* @brief Add a laser scan to the navigation system.
|
||||
* @param laser_scan_name The name of the laser scan.
|
||||
* @param laser_scan The laser scan to add.
|
||||
*/
|
||||
virtual void addLaserScan(const std::string &laser_scan_name, robot_sensor_msgs::LaserScan laser_scan) override;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Add a point cloud to the navigation system.
|
||||
* @param point_cloud_name The name of the point cloud.
|
||||
* @param point_cloud The point cloud to add.
|
||||
*/
|
||||
virtual void addPointCloud(const std::string &point_cloud_name, robot_sensor_msgs::PointCloud point_cloud) override;
|
||||
|
||||
/**
|
||||
* @brief Add a point cloud2 to the navigation system.
|
||||
* @param point_cloud2_name The name of the point cloud2.
|
||||
* @param point_cloud2 The point cloud2 to add.
|
||||
*/
|
||||
virtual void addPointCloud2(const std::string &point_cloud2_name, robot_sensor_msgs::PointCloud2 point_cloud2) override;
|
||||
|
||||
/**
|
||||
* @brief Add one coherent depth-camera sample to the navigation system.
|
||||
* @param topic The logical topic of the combined depth-camera stream.
|
||||
* @param data Depth image and matching camera intrinsics.
|
||||
*/
|
||||
virtual void addDepthCameraData(const std::string &topic,
|
||||
robot_sensor_msgs::DepthCameraData::ConstPtr data) override;
|
||||
|
||||
/**
|
||||
* @brief Get a static map from the navigation system.
|
||||
* @param map_name The name of the map.
|
||||
* @return The map.
|
||||
*/
|
||||
virtual robot_nav_msgs::OccupancyGrid getStaticMap(const std::string &map_name) override;
|
||||
|
||||
/**
|
||||
* @brief Get a laser scan from the navigation system.
|
||||
* @param laser_scan_name The name of the laser scan.
|
||||
* @return The laser scan.
|
||||
*/
|
||||
virtual robot_sensor_msgs::LaserScan getLaserScan(const std::string &laser_scan_name) override;
|
||||
|
||||
/**
|
||||
* @brief Get a point cloud from the navigation system.
|
||||
* @param point_cloud_name The name of the point cloud.
|
||||
* @return The point cloud.
|
||||
*/
|
||||
virtual robot_sensor_msgs::PointCloud getPointCloud(const std::string &point_cloud_name) override;
|
||||
|
||||
/**
|
||||
* @brief Get a point cloud2 from the navigation system.
|
||||
* @param point_cloud2_name The name of the point cloud2.
|
||||
* @return The point cloud2.
|
||||
*/
|
||||
virtual robot_sensor_msgs::PointCloud2 getPointCloud2(const std::string &point_cloud2_name) override;
|
||||
|
||||
/**
|
||||
* @brief Get all static maps from the navigation system.
|
||||
* @return The static maps.
|
||||
*/
|
||||
virtual std::map<std::string, robot_nav_msgs::OccupancyGrid> getAllStaticMaps() override;
|
||||
|
||||
/**
|
||||
* @brief Get all laser scans from the navigation system.
|
||||
* @return The laser scans.
|
||||
*/
|
||||
virtual std::map<std::string, robot_sensor_msgs::LaserScan> getAllLaserScans() override;
|
||||
|
||||
/**
|
||||
* @brief Get all point clouds from the navigation system.
|
||||
* @return The point clouds.
|
||||
*/
|
||||
virtual std::map<std::string, robot_sensor_msgs::PointCloud> getAllPointClouds() override;
|
||||
|
||||
/**
|
||||
* @brief Get all point cloud2s from the navigation system.
|
||||
* @return The point cloud2s.
|
||||
*/
|
||||
virtual std::map<std::string, robot_sensor_msgs::PointCloud2> getAllPointCloud2s() override;
|
||||
|
||||
/**
|
||||
* @brief Remove a static map from the navigation system.
|
||||
* @param map_name The name of the map.
|
||||
* @return True if the map was removed successfully.
|
||||
*/
|
||||
virtual bool removeStaticMap(const std::string &map_name) override;
|
||||
|
||||
/**
|
||||
* @brief Remove a laser scan from the navigation system.
|
||||
* @param laser_scan_name The name of the laser scan.
|
||||
* @return True if the laser scan was removed successfully.
|
||||
*/
|
||||
virtual bool removeLaserScan(const std::string &laser_scan_name) override;
|
||||
|
||||
/**
|
||||
* @brief Remove a point cloud from the navigation system.
|
||||
* @param point_cloud_name The name of the point cloud.
|
||||
* @return True if the point cloud was removed successfully.
|
||||
*/
|
||||
virtual bool removePointCloud(const std::string &point_cloud_name) override;
|
||||
|
||||
/**
|
||||
* @brief Remove a point cloud2 from the navigation system.
|
||||
* @param point_cloud2_name The name of the point cloud2.
|
||||
* @return True if the point cloud2 was removed successfully.
|
||||
*/
|
||||
virtual bool removePointCloud2(const std::string &point_cloud2_name) override;
|
||||
|
||||
/**
|
||||
* @brief Remove all static maps from the navigation system.
|
||||
* @return True if the static maps were removed successfully.
|
||||
*/
|
||||
virtual bool removeAllStaticMaps() override;
|
||||
|
||||
/**
|
||||
* @brief Remove all laser scans from the navigation system.
|
||||
* @return True if the laser scans were removed successfully.
|
||||
*/
|
||||
virtual bool removeAllLaserScans() override;
|
||||
|
||||
/**
|
||||
* @brief Remove all point clouds from the navigation system.
|
||||
* @return True if the point clouds were removed successfully.
|
||||
*/
|
||||
virtual bool removeAllPointClouds() override;
|
||||
|
||||
/**
|
||||
* @brief Remove all point cloud2s from the navigation system.
|
||||
* @return True if the point cloud2s were removed successfully.
|
||||
*/
|
||||
virtual bool removeAllPointCloud2s() override;
|
||||
|
||||
/**
|
||||
* @brief Remove all data from the navigation system.
|
||||
* @return True if the data was removed successfully.
|
||||
*/
|
||||
virtual bool removeAllData() override;
|
||||
|
||||
/**
|
||||
* @brief Add an odometry to the navigation system.
|
||||
* @param odometry_name The name of the odometry.
|
||||
* @param odometry The odometry to add.
|
||||
*/
|
||||
virtual void addOdometry(const std::string &odometry_name, robot_nav_msgs::Odometry odometry) override;
|
||||
|
||||
/**
|
||||
* @brief Send a goal for the robot to navigate to.
|
||||
* @param goal Target pose in the global frame.
|
||||
* @param xy_goal_tolerance Acceptable error in X/Y (meters).
|
||||
* @param yaw_goal_tolerance Acceptable angular error (radians).
|
||||
* @return True if goal was accepted and sent successfully.
|
||||
*/
|
||||
virtual bool moveTo(const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Send a goal for the robot to navigate to.
|
||||
* @param msg Order message.
|
||||
* @param goal Target pose in the global frame.
|
||||
* @param xy_goal_tolerance Acceptable error in X/Y (meters).
|
||||
* @param yaw_goal_tolerance Acceptable angular error (radians).
|
||||
* @return True if goal was accepted and sent successfully.
|
||||
*/
|
||||
virtual bool moveTo(const robot_protocol_msgs::Order &msg,
|
||||
const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Send a docking goal to a predefined marker (e.g. charger).
|
||||
* @param maker Marker name or ID.
|
||||
* @param goal Target pose for docking.
|
||||
* @param xy_goal_tolerance Acceptable XY error (meters).
|
||||
* @param yaw_goal_tolerance Acceptable heading error (radians).
|
||||
* @return True if docking command succeeded.
|
||||
*/
|
||||
virtual bool dockTo(const std::string &maker,
|
||||
const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Send a docking goal to a predefined marker (e.g. charger).
|
||||
* @param msg Order message.
|
||||
* @param goal Target pose for docking.
|
||||
* @param xy_goal_tolerance Acceptable XY error (meters).
|
||||
* @param yaw_goal_tolerance Acceptable heading error (radians).
|
||||
* @return True if docking command succeeded.
|
||||
*/
|
||||
virtual bool dockTo(const robot_protocol_msgs::Order &msg,
|
||||
const std::string &marker,
|
||||
const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0,
|
||||
double yaw_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Move straight toward the target position (X-axis).
|
||||
* @param msg Order message.
|
||||
* @param goal Target pose.
|
||||
* @param xy_goal_tolerance Acceptable positional error (meters).
|
||||
* @return True if command issued successfully.
|
||||
*/
|
||||
virtual bool moveStraightTo(const robot_geometry_msgs::PoseStamped &goal,
|
||||
double xy_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Rotate in place to align with target orientation.
|
||||
* @param goal Pose containing desired heading (only Z-axis used).
|
||||
* @param yaw_goal_tolerance Acceptable angular error (radians).
|
||||
* @return True if rotation command was sent successfully.
|
||||
*/
|
||||
virtual bool rotateTo(const robot_geometry_msgs::PoseStamped &goal,
|
||||
double yaw_goal_tolerance = 0.0) override;
|
||||
|
||||
/**
|
||||
* @brief Pause the robot's movement (e.g. during obstacle avoidance).
|
||||
*/
|
||||
virtual void pause() override;
|
||||
|
||||
/**
|
||||
* @brief Resume motion after a pause.
|
||||
*/
|
||||
virtual void resume() override;
|
||||
|
||||
/**
|
||||
* @brief Cancel the current goal and stop the robot.
|
||||
*/
|
||||
virtual void cancel() override;
|
||||
|
||||
/**
|
||||
* @brief Send direct linear velocity command.
|
||||
* @param linear Linear velocity vector (x, y, z).
|
||||
* @return True if the command was accepted.
|
||||
*/
|
||||
virtual bool setTwistLinear(const robot_geometry_msgs::Vector3 &linear) override;
|
||||
|
||||
/**
|
||||
* @brief Send limited angular velocity command.
|
||||
* @param angular Angular velocity vector (x, y, z).
|
||||
* @return True if the command was accepted.
|
||||
*/
|
||||
virtual bool setTwistAngular(const robot_geometry_msgs::Vector3 &angular) override;
|
||||
|
||||
/**
|
||||
* @brief Get the robot’s pose as a PoseStamped.
|
||||
* @param pose Output parameter with the robot’s current pose.
|
||||
* @return True if pose was successfully retrieved.
|
||||
*/
|
||||
virtual bool getRobotPose(robot_geometry_msgs::PoseStamped &pose) override;
|
||||
|
||||
/**
|
||||
* @brief Get the robot’s pose as a 2D pose.
|
||||
* @param pose Output parameter with the robot’s current 2D pose.
|
||||
* @return True if pose was successfully retrieved.
|
||||
*/
|
||||
virtual bool getRobotPose(robot_geometry_msgs::Pose2D &pose) override;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get the robot’s twist.
|
||||
* @return The robot’s current twist.
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped getTwist() override;
|
||||
|
||||
/**
|
||||
* @brief Get the navigation feedback.
|
||||
* @return Pointer to the navigation feedback.
|
||||
*/
|
||||
virtual robot::move_base_core::NavFeedback *getFeedback() override;
|
||||
|
||||
/**
|
||||
* @brief Get the global data.
|
||||
* @return The global data.
|
||||
*/
|
||||
virtual robot::move_base_core::PlannerDataOutput getGlobalData() override;
|
||||
|
||||
/**
|
||||
* @brief Get the local data.
|
||||
* @return The local data.
|
||||
*/
|
||||
virtual robot::move_base_core::PlannerDataOutput getLocalData() override;
|
||||
|
||||
/**
|
||||
* @brief Destructor - Cleans up
|
||||
*/
|
||||
virtual ~MoveBase();
|
||||
|
||||
/**
|
||||
* @brief Create a new MoveBase
|
||||
* @return A shared pointer to the new MoveBase
|
||||
*/
|
||||
static robot::move_base_core::BaseNavigation::Ptr create();
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* @brief Update the global costmap.
|
||||
* @param value The value to update the costmap.
|
||||
* @param layer_type The type of the layer.
|
||||
* @param name The name of the costmap.
|
||||
*/
|
||||
template<typename T>
|
||||
void updateGlobalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name);
|
||||
|
||||
/**
|
||||
* @brief Update the local costmap.
|
||||
* @param value The value to update the costmap.
|
||||
* @param layer_type The type of the layer.
|
||||
* @param name The name of the costmap.
|
||||
*/
|
||||
template<typename T>
|
||||
void updateLocalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name);
|
||||
|
||||
/**
|
||||
* @brief Performs a control cycle
|
||||
* @param goal A reference to the goal to pursue
|
||||
* @return True if processing of the goal is done, false otherwise
|
||||
*/
|
||||
bool executeCycle(robot_geometry_msgs::PoseStamped &goal);
|
||||
|
||||
/**
|
||||
* @brief Set velocity for yaw goal tolerance of the robot
|
||||
* @param yaw_goal_tolerance the value command
|
||||
*/
|
||||
void setYawGoalTolerance(double yaw_goal_tolerance);
|
||||
|
||||
/**
|
||||
* @brief Set the XY goal tolerance for the robot
|
||||
* @param xy_goal_tolerance The XY tolerance value in meters
|
||||
*/
|
||||
void setXyGoalTolerance(double xy_goal_tolerance);
|
||||
|
||||
/**
|
||||
* @brief Swaps the current global planner with a new one specified by name
|
||||
* @param base_global_planner The name of the new global planner to use
|
||||
*/
|
||||
void swapPlanner(std::string base_global_planner);
|
||||
|
||||
/**
|
||||
* @brief Make a new global plan
|
||||
* @param goal The goal to plan to
|
||||
* @param plan Will be filled in with the plan made by the planner
|
||||
* @return True if planning succeeds, false otherwise
|
||||
*/
|
||||
bool makePlan(const robot_geometry_msgs::PoseStamped &goal, std::vector<robot_geometry_msgs::PoseStamped> &plan);
|
||||
|
||||
/**
|
||||
* @brief Make a new global plan
|
||||
* @param msg The order message
|
||||
* @param goal The goal to plan to
|
||||
* @param plan Will be filled in with the plan made by the planner
|
||||
* @return True if planning succeeds, false otherwise
|
||||
*/
|
||||
bool makePlan(const robot_protocol_msgs::Order &msg, const robot_geometry_msgs::PoseStamped &goal, std::vector<robot_geometry_msgs::PoseStamped> &plan);
|
||||
|
||||
/**
|
||||
* @brief Load the recovery behaviors for the navigation stack from the parameter server
|
||||
* @return True if the recovery behaviors were loaded successfully, false otherwise
|
||||
*/
|
||||
bool loadRecoveryBehaviors(const robot::NodeHandle &node);
|
||||
|
||||
/**
|
||||
* @brief Loads the default recovery behaviors for the navigation stack
|
||||
*/
|
||||
void loadDefaultRecoveryBehaviors();
|
||||
|
||||
/**
|
||||
* @brief Clears obstacles within a window around the robot
|
||||
* @param size_x The x size of the window
|
||||
* @param size_y The y size of the window
|
||||
*/
|
||||
void clearCostmapWindows(double size_x, double size_y);
|
||||
|
||||
/**
|
||||
* @brief Publishes a velocity command of zero to the base
|
||||
*/
|
||||
void publishZeroVelocity();
|
||||
|
||||
/**
|
||||
* @brief Reset the state of the move_base action and send a zero velocity command to the base
|
||||
*/
|
||||
void resetState();
|
||||
|
||||
|
||||
/**
|
||||
* @brief Thread function that continuously plans paths to the goal
|
||||
*/
|
||||
void planThread();
|
||||
|
||||
/**
|
||||
* @brief Callback function to execute a move_base goal
|
||||
* @param move_base_goal The goal message to execute
|
||||
*/
|
||||
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr &move_base_goal);
|
||||
|
||||
/**
|
||||
* @brief Setup callbacks for the action server
|
||||
*/
|
||||
void setupActionServerCallbacks();
|
||||
|
||||
/**
|
||||
* @brief Check if a quaternion is valid (normalized)
|
||||
* @param q The quaternion to validate
|
||||
* @return True if the quaternion is valid, false otherwise
|
||||
*/
|
||||
bool isQuaternionValid(const robot_geometry_msgs::Quaternion &q);
|
||||
|
||||
/**
|
||||
* @brief Get the robot's pose in the global frame using a specific costmap
|
||||
* @param global_pose Output parameter with the robot's current pose
|
||||
* @param costmap The costmap to use for pose lookup
|
||||
* @return True if pose was successfully retrieved
|
||||
*/
|
||||
bool getRobotPose(robot_geometry_msgs::PoseStamped &global_pose, robot_costmap_2d::Costmap2DROBOT *costmap);
|
||||
|
||||
/**
|
||||
* @brief Calculate the Euclidean distance between two poses
|
||||
* @param p1 First pose
|
||||
* @param p2 Second pose
|
||||
* @return The distance between the two poses in meters
|
||||
*/
|
||||
double distance(const robot_geometry_msgs::PoseStamped &p1, const robot_geometry_msgs::PoseStamped &p2);
|
||||
|
||||
/**
|
||||
* @brief Transform a goal pose to the global frame
|
||||
* @param goal_pose_msg The goal pose to transform
|
||||
* @return The transformed pose in the global frame
|
||||
*/
|
||||
robot_geometry_msgs::PoseStamped goalToGlobalFrame(const robot_geometry_msgs::PoseStamped &goal_pose_msg);
|
||||
|
||||
/**
|
||||
* @brief This is used to wake the planner at periodic intervals.
|
||||
*/
|
||||
void wakePlanner(const robot::TimerEvent &event);
|
||||
|
||||
private:
|
||||
/** @brief Flag indicating if the move_base has been initialized */
|
||||
bool initialized_;
|
||||
/** @brief Transform listener for coordinate frame transformations */
|
||||
robot::TFListenerPtr tf_;
|
||||
/** @brief Private node handle for ROS parameters and topics */
|
||||
robot::NodeHandle private_nh_;
|
||||
|
||||
/** @brief Action server for move_base goals */
|
||||
MoveBaseActionServer *as_;
|
||||
|
||||
/** @brief Function loader for global planner plugins */
|
||||
boost::function<robot_nav_core::BaseGlobalPlanner::Ptr()> planner_loader_;
|
||||
/** @brief Function loader for local planner (controller) plugins */
|
||||
boost::function<robot_nav_core::BaseLocalPlanner::Ptr()> controller_loader_;
|
||||
/** @brief Map of recovery behavior loaders by name */
|
||||
std::map<std::string, boost::function<robot_nav_core::RecoveryBehavior::Ptr()>> recovery_loaders_;
|
||||
|
||||
/** @brief Local planner (trajectory controller) instance */
|
||||
robot_nav_core::BaseLocalPlanner::Ptr tc_;
|
||||
/** @brief Global planner instance */
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr planner_;
|
||||
/** @brief Vector of recovery behavior instances */
|
||||
std::vector<robot_nav_core::RecoveryBehavior::Ptr> recovery_behaviors_;
|
||||
|
||||
/** @brief Costmap for the local planner/controller */
|
||||
robot_costmap_2d::Costmap2DROBOT *controller_costmap_robot_;
|
||||
/** @brief Costmap for the global planner */
|
||||
robot_costmap_2d::Costmap2DROBOT *planner_costmap_robot_;
|
||||
/** @brief Robot base frame name and global frame name */
|
||||
std::string robot_base_frame_, global_frame_;
|
||||
/** @brief Names of recovery behaviors to use */
|
||||
std::vector<std::string> recovery_behavior_names_;
|
||||
/** @brief Current index in the recovery behavior list */
|
||||
unsigned int recovery_index_;
|
||||
/** @brief Flag indicating if recovery behaviors are enabled */
|
||||
bool recovery_behavior_enabled_;
|
||||
|
||||
/** @brief Current global pose of the robot */
|
||||
robot_geometry_msgs::PoseStamped global_pose_;
|
||||
/** @brief Frequency for planner execution (Hz) */
|
||||
double planner_frequency_;
|
||||
/** @brief Frequency for controller execution (Hz) */
|
||||
double controller_frequency_;
|
||||
/** @brief Inscribed radius of the robot footprint (meters) */
|
||||
double inscribed_radius_;
|
||||
/** @brief Circumscribed radius of the robot footprint (meters) */
|
||||
double circumscribed_radius_;
|
||||
/** @brief Maximum time to wait for a valid plan before triggering recovery (seconds) */
|
||||
double planner_patience_;
|
||||
/** @brief Maximum time to wait for valid control before triggering recovery (seconds) */
|
||||
double controller_patience_;
|
||||
/** @brief Maximum number of planning retries before giving up */
|
||||
int32_t max_planning_retries_;
|
||||
/** @brief Current number of planning retries */
|
||||
uint32_t planning_retries_;
|
||||
/** @brief Conservative distance threshold for resetting costmaps (meters) */
|
||||
double conservative_reset_dist_;
|
||||
/** @brief Radius around robot to clear obstacles during recovery (meters) */
|
||||
double clearing_radius_;
|
||||
/** @brief Flag to shutdown costmaps when not in use */
|
||||
bool shutdown_costmaps_;
|
||||
/** @brief Flag allowing rotation during costmap clearing */
|
||||
bool clearing_rotation_allowed_;
|
||||
/** @brief Flag to clear costmap when making a new plan */
|
||||
bool make_plan_clear_costmap_;
|
||||
/** @brief Flag to add unreachable goals to costmap */
|
||||
bool make_plan_add_unreachable_goal_;
|
||||
/** @brief Time threshold for detecting oscillation (seconds) */
|
||||
double oscillation_timeout_;
|
||||
/** @brief Distance threshold for detecting oscillation (meters) */
|
||||
double oscillation_distance_;
|
||||
|
||||
/** @brief Current state of the move_base (PLANNING, CONTROLLING, CLEARING) */
|
||||
MoveBaseState state_;
|
||||
/** @brief Trigger that caused recovery behavior (PLANNING_R, CONTROLLING_R, OSCILLATION_R) */
|
||||
RecoveryTrigger recovery_trigger_;
|
||||
|
||||
/** @brief Timestamp of the last valid plan */
|
||||
robot::Time last_valid_plan_;
|
||||
/** @brief Timestamp of the last valid control command */
|
||||
robot::Time last_valid_control_;
|
||||
/** @brief Timestamp of the last oscillation reset */
|
||||
robot::Time last_oscillation_reset_;
|
||||
/** @brief Pose used for oscillation detection */
|
||||
robot_geometry_msgs::PoseStamped oscillation_pose_;
|
||||
|
||||
/** @brief Plan triple buffer: plan from the planner thread */
|
||||
std::vector<robot_geometry_msgs::PoseStamped> *planner_plan_;
|
||||
/** @brief Plan triple buffer: latest plan (intermediate buffer) */
|
||||
std::vector<robot_geometry_msgs::PoseStamped> *latest_plan_;
|
||||
/** @brief Plan triple buffer: plan used by the controller */
|
||||
std::vector<robot_geometry_msgs::PoseStamped> *controller_plan_;
|
||||
|
||||
/** @brief Flag to control planner thread execution */
|
||||
bool runPlanner_;
|
||||
/** @brief Mutex for protecting planner thread data */
|
||||
boost::recursive_mutex planner_mutex_;
|
||||
/** @brief Condition variable to wake planner thread */
|
||||
boost::condition_variable_any planner_cond_;
|
||||
/** @brief Goal pose for the planner thread */
|
||||
robot_geometry_msgs::PoseStamped planner_goal_;
|
||||
/** @brief Order message for the planner thread (nullptr if not using Order-based planning) */
|
||||
boost::shared_ptr<robot_protocol_msgs::Order> planner_order_;
|
||||
/** @brief Thread handle for the planner */
|
||||
boost::thread *planner_thread_;
|
||||
|
||||
/** @brief Mutex for protecting configuration changes */
|
||||
boost::recursive_mutex configuration_mutex_;
|
||||
/** @brief Last configuration used */
|
||||
move_base::MoveBaseConfig last_config_;
|
||||
/** @brief Default configuration */
|
||||
move_base::MoveBaseConfig default_config_;
|
||||
|
||||
/** @brief Flag indicating if setup is complete */
|
||||
bool setup_;
|
||||
/** @brief Flag indicating planner frequency changed */
|
||||
bool p_freq_change_;
|
||||
/** @brief Flag indicating controller frequency changed */
|
||||
bool c_freq_change_;
|
||||
/** @brief Flag indicating a new global plan is available */
|
||||
bool new_global_plan_;
|
||||
/** @brief Flag indicating cancel control request */
|
||||
bool cancel_ctr_;
|
||||
/** @brief Flag indicating pause control request */
|
||||
bool pause_ctr_;
|
||||
/** @brief Flag indicating if robot is currently paused */
|
||||
bool paused_;
|
||||
/** @brief Minimum linear velocity when approaching goal (m/s) */
|
||||
double min_approach_linear_velocity_{0.1};
|
||||
/** @brief Previous forward linear velocity command */
|
||||
robot_geometry_msgs::Vector3 old_linear_fwd_;
|
||||
/** @brief Previous backward linear velocity command */
|
||||
robot_geometry_msgs::Vector3 old_linear_bwd_;
|
||||
/** @brief Previous forward angular velocity command */
|
||||
robot_geometry_msgs::Vector3 old_angular_fwd_;
|
||||
/** @brief Previous reverse angular velocity command */
|
||||
robot_geometry_msgs::Vector3 old_angular_rev_;
|
||||
/** @brief Original XY goal tolerance value (meters) */
|
||||
double original_xy_goal_tolerance_;
|
||||
/** @brief Original yaw goal tolerance value (radians) */
|
||||
double original_yaw_goal_tolerance_;
|
||||
|
||||
/** @brief Name of the position/local planner plugin */
|
||||
std::string position_planner_name_{"MKTLocalPlanner"};
|
||||
/** @brief Name of the docking planner plugin */
|
||||
std::string docking_planner_name_{"NAVDockingLocalPlanner"};
|
||||
/** @brief Name of the go-straight planner plugin */
|
||||
std::string go_straight_planner_name_{"NAVGoStraightLocalPlanner"};
|
||||
/** @brief Name of the rotate planner plugin */
|
||||
std::string rotate_planner_name_{"NAVRotateLocalPlanner"};
|
||||
|
||||
};
|
||||
|
||||
} // namespace move_base
|
||||
|
||||
#endif // NAV_MOVE_BASE_ACTION_H_
|
||||
@@ -1,259 +0,0 @@
|
||||
#ifndef MOVE_BASE_SIMPLE_ACTION_SERVER_H_
|
||||
#define MOVE_BASE_SIMPLE_ACTION_SERVER_H_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <boost/thread.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <boost/thread/mutex.hpp>
|
||||
#include <boost/thread/condition_variable.hpp>
|
||||
|
||||
// Action message types
|
||||
#include <robot_move_base_msgs/MoveBaseAction.h>
|
||||
#include <robot_move_base_msgs/MoveBaseActionGoal.h>
|
||||
#include <robot_move_base_msgs/MoveBaseActionResult.h>
|
||||
#include <robot_move_base_msgs/MoveBaseActionFeedback.h>
|
||||
#include <robot_move_base_msgs/MoveBaseGoal.h>
|
||||
#include <robot_move_base_msgs/MoveBaseResult.h>
|
||||
#include <robot_move_base_msgs/MoveBaseFeedback.h>
|
||||
|
||||
// Actionlib message types
|
||||
#include <robot_actionlib_msgs/GoalID.h>
|
||||
#include <robot_actionlib_msgs/GoalStatus.h>
|
||||
#include <robot_actionlib_msgs/GoalStatusArray.h>
|
||||
|
||||
// Robot framework
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
|
||||
/**
|
||||
* @class SimpleActionServer
|
||||
* @brief A simplified action server implementation similar to ROS actionlib::SimpleActionServer
|
||||
*
|
||||
* This class provides a simple interface for implementing action servers without ROS dependency.
|
||||
* It handles goal requests, preemption, feedback publishing, and result publishing using callback functions.
|
||||
*
|
||||
* @tparam ActionSpec The action message type (e.g., robot_move_base_msgs::MoveBaseAction)
|
||||
*/
|
||||
template<class ActionSpec>
|
||||
class SimpleActionServer
|
||||
{
|
||||
public:
|
||||
// Typedefs for action message types
|
||||
typedef typename ActionSpec::_action_goal_type ActionGoal;
|
||||
typedef typename ActionSpec::_action_result_type ActionResult;
|
||||
typedef typename ActionSpec::_action_feedback_type ActionFeedback;
|
||||
|
||||
typedef typename ActionGoal::_goal_type Goal;
|
||||
typedef typename ActionResult::_result_type Result;
|
||||
typedef typename ActionFeedback::_feedback_type Feedback;
|
||||
|
||||
typedef boost::shared_ptr<const Goal> GoalConstPtr;
|
||||
typedef boost::shared_ptr<const Result> ResultConstPtr;
|
||||
typedef boost::shared_ptr<const Feedback> FeedbackConstPtr;
|
||||
typedef typename ActionGoal::ConstPtr ActionGoalConstPtr;
|
||||
typedef typename ActionResult::ConstPtr ActionResultConstPtr;
|
||||
typedef typename ActionFeedback::ConstPtr ActionFeedbackConstPtr;
|
||||
typedef robot_actionlib_msgs::GoalStatusArrayConstPtr GoalStatusArrayConstPtr;
|
||||
|
||||
// Callback function types
|
||||
typedef std::function<void(const ActionGoalConstPtr&)> GoalCallback;
|
||||
typedef std::function<void(const robot_actionlib_msgs::GoalIDConstPtr&)> CancelCallback;
|
||||
typedef std::function<void(const ActionFeedbackConstPtr&)> FeedbackCallback;
|
||||
typedef std::function<void(const ActionResultConstPtr&)> ResultCallback;
|
||||
typedef std::function<void(const GoalStatusArrayConstPtr&)> StatusCallback;
|
||||
typedef std::function<void(const GoalConstPtr&)> ExecuteCallback;
|
||||
|
||||
// Typedefs for non-const pointers
|
||||
typedef typename ActionResult::Ptr ActionResultPtr;
|
||||
typedef typename ActionFeedback::Ptr ActionFeedbackPtr;
|
||||
|
||||
/**
|
||||
* @brief Constructor
|
||||
* @param name Action name (e.g., "move_base")
|
||||
* @param execute_callback Callback function to execute when a goal is received
|
||||
* @param auto_start If true, automatically start the server
|
||||
*/
|
||||
SimpleActionServer(const std::string& name,
|
||||
ExecuteCallback execute_callback,
|
||||
bool auto_start = true);
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
~SimpleActionServer();
|
||||
|
||||
/**
|
||||
* @brief Start the action server
|
||||
*/
|
||||
void start();
|
||||
|
||||
/**
|
||||
* @brief Stop the action server
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* @brief Set callback for goal messages
|
||||
* @param callback Function to call when a goal is received
|
||||
*/
|
||||
void setGoalCallback(GoalCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set callback for cancel messages
|
||||
* @param callback Function to call when a cancel is received
|
||||
*/
|
||||
void setCancelCallback(CancelCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set callback for feedback publishing
|
||||
* @param callback Function to call when feedback needs to be published
|
||||
*/
|
||||
void setFeedbackCallback(FeedbackCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set callback for result publishing
|
||||
* @param callback Function to call when result needs to be published
|
||||
*/
|
||||
void setResultCallback(ResultCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set callback for status publishing
|
||||
* @param callback Function to call when status needs to be published
|
||||
*/
|
||||
void setStatusCallback(StatusCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set status publish rate
|
||||
* @param rate Publishing rate in Hz
|
||||
*/
|
||||
void setStatusPublishRate(double rate);
|
||||
|
||||
/**
|
||||
* @brief Process an incoming goal message
|
||||
* @param goal_msg The goal message to process
|
||||
*/
|
||||
void processGoal(const ActionGoalConstPtr& goal_msg);
|
||||
|
||||
/**
|
||||
* @brief Process an incoming cancel message
|
||||
* @param cancel_msg The cancel message to process
|
||||
*/
|
||||
void processCancel(const robot_actionlib_msgs::GoalIDConstPtr& cancel_msg);
|
||||
|
||||
/**
|
||||
* @brief Check if a new goal is available
|
||||
* @return True if a new goal is available
|
||||
*/
|
||||
bool isNewGoalAvailable();
|
||||
|
||||
/**
|
||||
* @brief Check if preemption has been requested
|
||||
* @return True if preemption has been requested
|
||||
*/
|
||||
bool isPreemptRequested();
|
||||
|
||||
/**
|
||||
* @brief Accept a new goal
|
||||
* @return The new goal, or nullptr if no new goal is available
|
||||
*/
|
||||
GoalConstPtr acceptNewGoal();
|
||||
|
||||
/**
|
||||
* @brief Set the action as succeeded
|
||||
* @param result The result to send
|
||||
* @param text Success message
|
||||
*/
|
||||
void setSucceeded(const Result& result = Result(), const std::string& text = "");
|
||||
|
||||
/**
|
||||
* @brief Set the action as aborted
|
||||
* @param result The result to send
|
||||
* @param text Error message
|
||||
*/
|
||||
void setAborted(const Result& result = Result(), const std::string& text = "");
|
||||
|
||||
/**
|
||||
* @brief Set the action as preempted
|
||||
* @param result The result to send
|
||||
* @param text Message
|
||||
*/
|
||||
void setPreempted(const Result& result = Result(), const std::string& text = "");
|
||||
|
||||
/**
|
||||
* @brief Publish feedback
|
||||
* @param feedback The feedback to publish
|
||||
*/
|
||||
void publishFeedback(const Feedback& feedback);
|
||||
|
||||
/**
|
||||
* @brief Get the current goal
|
||||
* @return The current goal, or nullptr if no goal is active
|
||||
*/
|
||||
GoalConstPtr getCurrentGoal();
|
||||
|
||||
/**
|
||||
* @brief Get the current status
|
||||
* @return The current goal status
|
||||
*/
|
||||
robot_actionlib_msgs::GoalStatus getCurrentStatus();
|
||||
|
||||
/**
|
||||
* @brief Check if the server is active
|
||||
* @return True if the server is active
|
||||
*/
|
||||
bool isActive();
|
||||
|
||||
/**
|
||||
* @brief Get the action name
|
||||
* @return The action name
|
||||
*/
|
||||
std::string getName() const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Execute the goal in a separate thread
|
||||
*/
|
||||
void executeGoal();
|
||||
|
||||
/**
|
||||
* @brief Thread function to publish status periodically
|
||||
*/
|
||||
void statusPublishThread();
|
||||
|
||||
// Action name
|
||||
std::string name_;
|
||||
|
||||
// Execute callback
|
||||
ExecuteCallback execute_callback_;
|
||||
|
||||
// Callbacks for external communication
|
||||
GoalCallback goal_callback_;
|
||||
CancelCallback cancel_callback_;
|
||||
FeedbackCallback feedback_callback_;
|
||||
ResultCallback result_callback_;
|
||||
StatusCallback status_callback_;
|
||||
|
||||
// State
|
||||
boost::mutex state_mutex_;
|
||||
boost::condition_variable goal_condition_;
|
||||
bool active_;
|
||||
bool preempt_requested_;
|
||||
bool new_goal_available_;
|
||||
GoalConstPtr goal_;
|
||||
robot_actionlib_msgs::GoalID current_goal_id_;
|
||||
robot_actionlib_msgs::GoalStatus current_status_;
|
||||
double status_publish_rate_;
|
||||
|
||||
// Threads
|
||||
boost::thread status_thread_;
|
||||
boost::thread execute_thread_;
|
||||
};
|
||||
|
||||
} // namespace move_base
|
||||
#endif // MOVE_BASE_SIMPLE_ACTION_SERVER_H_
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
<package>
|
||||
<name>move_base</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
move_base is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. move_base
|
||||
maintains the relationship between coordinate frames in a tree
|
||||
structure buffered in time, and lets the user transform points,
|
||||
vectors, etc between any two coordinate frames at any desired
|
||||
point in time.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/move_base</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>geometry_msgs</build_depend>
|
||||
<run_depend>geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_std_msgs</build_depend>
|
||||
<run_depend>robot_std_msgs</run_depend>
|
||||
|
||||
<build_depend>move_base_core</build_depend>
|
||||
<run_depend>move_base_core</run_depend>
|
||||
|
||||
<build_depend>robot_nav_core</build_depend>
|
||||
<run_depend>robot_nav_core</run_depend>
|
||||
|
||||
<build_depend>robot_costmap_2d</build_depend>
|
||||
<run_depend>robot_costmap_2d</run_depend>
|
||||
|
||||
<build_depend>robot_tf3_sensor_msgs</build_depend>
|
||||
<run_depend>robot_tf3_sensor_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_tf3_geometry_msgs</build_depend>
|
||||
<run_depend>robot_tf3_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>data_convert</build_depend>
|
||||
<run_depend>data_convert</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
|
||||
<build_depend>mission_adapters</build_depend>
|
||||
<run_depend>mission_adapters</run_depend>
|
||||
|
||||
<build_depend>robot_move_base_msgs</build_depend>
|
||||
<run_depend>robot_move_base_msgs</run_depend>
|
||||
|
||||
</package>
|
||||
@@ -1,130 +0,0 @@
|
||||
#include <move_base/convert_data.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
char* move_base::ConvertData::cost_translation_table_ = NULL;
|
||||
|
||||
move_base::ConvertData::ConvertData(robot_costmap_2d::Costmap2DROBOT* costmap, std::string global_frame, bool always_send_full_costmap)
|
||||
: costmap_(costmap), global_frame_(global_frame), always_send_full_costmap_(always_send_full_costmap)
|
||||
{
|
||||
if (cost_translation_table_ == NULL)
|
||||
{
|
||||
cost_translation_table_ = new char[256];
|
||||
|
||||
// special values:
|
||||
cost_translation_table_[(const int)robot_costmap_2d::PREFERRED_SPACE] = 120; // Preferred place
|
||||
for(int i = (int)robot_costmap_2d::PREFERRED_SPACE+1; i <= (const int)robot_costmap_2d::FREE_SPACE; i++)
|
||||
cost_translation_table_[i] = 0; // NO obstacle
|
||||
|
||||
cost_translation_table_[(const int)robot_costmap_2d::CRITICAL_SPACE] = 150; // CRITICAL_SPACE
|
||||
cost_translation_table_[(const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE] = 99; // INSCRIBED obstacle
|
||||
cost_translation_table_[(const int)robot_costmap_2d::LETHAL_OBSTACLE] = 100; // LETHAL obstacle
|
||||
cost_translation_table_[(const int)robot_costmap_2d::NO_INFORMATION] = -1; // UNKNOWN
|
||||
|
||||
// regular cost values scale the range 10 to 252 (inclusive) to fit
|
||||
// into 1 to 98 (inclusive).
|
||||
for (int i = (int)robot_costmap_2d::FREE_SPACE + 1; i < (const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE; i++)
|
||||
{
|
||||
cost_translation_table_[ i ] = char(1 + (97 * (i - 1)) / 251);
|
||||
}
|
||||
}
|
||||
|
||||
xn_ = yn_ = 0;
|
||||
x0_ = costmap_->getCostmap()->getSizeInCellsX();
|
||||
y0_ = costmap_->getCostmap()->getSizeInCellsY();
|
||||
}
|
||||
|
||||
move_base::ConvertData::~ConvertData()
|
||||
{
|
||||
}
|
||||
|
||||
// prepare grid_ message for publication.
|
||||
void move_base::ConvertData::prepareGrid()
|
||||
{
|
||||
// boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
|
||||
double resolution = costmap_->getCostmap()->getResolution();
|
||||
|
||||
grid_.header.frame_id = global_frame_;
|
||||
grid_.header.stamp = robot::Time::now();
|
||||
grid_.info.resolution = resolution;
|
||||
|
||||
grid_.info.width = costmap_->getCostmap()->getSizeInCellsX();
|
||||
grid_.info.height = costmap_->getCostmap()->getSizeInCellsY();
|
||||
|
||||
double wx, wy;
|
||||
costmap_->getCostmap()->mapToWorld(0, 0, wx, wy);
|
||||
grid_.info.origin.position.x = wx - resolution / 2;
|
||||
grid_.info.origin.position.y = wy - resolution / 2;
|
||||
grid_.info.origin.position.z = 0.0;
|
||||
grid_.info.origin.orientation.w = 1.0;
|
||||
saved_origin_x_ = costmap_->getCostmap()->getOriginX();
|
||||
saved_origin_y_ = costmap_->getCostmap()->getOriginY();
|
||||
|
||||
grid_.data.resize(grid_.info.width * grid_.info.height);
|
||||
|
||||
unsigned char* data = costmap_->getCostmap()->getCharMap();
|
||||
for (unsigned int i = 0; i < grid_.data.size(); i++)
|
||||
{
|
||||
grid_.data[i] = cost_translation_table_[ data[ i ]];
|
||||
}
|
||||
}
|
||||
|
||||
void move_base::ConvertData::updateCostmap(robot_nav_msgs::OccupancyGrid &grid, robot_map_msgs::OccupancyGridUpdate &update, bool &is_updated)
|
||||
{
|
||||
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(costmap_->getCostmap()->getMutex()));
|
||||
float resolution = costmap_->getCostmap()->getResolution();
|
||||
unsigned int x0, y0, xn, yn;
|
||||
costmap_->getLayeredCostmap()->getBounds(&x0, &xn, &y0, &yn);
|
||||
updateBounds(x0, xn, y0, yn);
|
||||
if (always_send_full_costmap_ || grid_.info.resolution != resolution ||
|
||||
grid_.info.width != costmap_->getCostmap()->getSizeInCellsX() ||
|
||||
grid_.info.height != costmap_->getCostmap()->getSizeInCellsY() ||
|
||||
saved_origin_x_ != costmap_->getCostmap()->getOriginX() ||
|
||||
saved_origin_y_ != costmap_->getCostmap()->getOriginY())
|
||||
{
|
||||
prepareGrid();
|
||||
grid = grid_;
|
||||
is_updated = false;
|
||||
}
|
||||
else if (x0_ < xn_)
|
||||
{
|
||||
update.header.stamp = robot::Time::now();
|
||||
update.header.frame_id = global_frame_;
|
||||
update.x = x0_;
|
||||
update.y = y0_;
|
||||
update.width = xn_ - x0_;
|
||||
update.height = yn_ - y0_;
|
||||
update.data.resize(update.width * update.height);
|
||||
|
||||
unsigned int i = 0;
|
||||
for (unsigned int y = y0_; y < yn_; y++)
|
||||
{
|
||||
for (unsigned int x = x0_; x < xn_; x++)
|
||||
{
|
||||
unsigned char cost = costmap_->getCostmap()->getCost(x, y);
|
||||
update.data[i++] = cost_translation_table_[ cost ];
|
||||
}
|
||||
}
|
||||
is_updated = true;
|
||||
}
|
||||
|
||||
xn_ = yn_ = 0;
|
||||
x0_ = costmap_->getCostmap()->getSizeInCellsX();
|
||||
y0_ = costmap_->getCostmap()->getSizeInCellsY();
|
||||
}
|
||||
|
||||
void move_base::ConvertData::updateFootprint(robot_geometry_msgs::PolygonStamped &footprint)
|
||||
{
|
||||
footprint.header.frame_id = global_frame_;
|
||||
footprint.header.stamp = robot::Time::now();
|
||||
footprint.polygon = costmap_->getRobotFootprintPolygonStamped().polygon;
|
||||
|
||||
}
|
||||
|
||||
void move_base::ConvertData::updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn)
|
||||
{
|
||||
x0_ = std::min(x0, x0_);
|
||||
xn_ = std::max(xn, xn_);
|
||||
y0_ = std::min(y0, y0_);
|
||||
yn_ = std::max(yn, yn_);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* 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 Willow Garage, Inc. 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.
|
||||
*/
|
||||
|
||||
#include <move_base/move_base.h>
|
||||
#include <iostream>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <tf3/transform_datatypes.h>
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
try {
|
||||
std::shared_ptr<tf3::BufferCore> tf = std::make_shared<tf3::BufferCore>();
|
||||
|
||||
// Lambda function để set static transform (tương tự tf_listener_set_static_transform trong nav_c_api.cpp)
|
||||
auto set_static_transform = [&tf](const std::string& parent_frame,
|
||||
const std::string& child_frame,
|
||||
double x, double y, double z,
|
||||
double qx, double qy, double qz, double qw) -> bool {
|
||||
if (!tf || parent_frame.empty() || child_frame.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
tf3::TransformStampedMsg st;
|
||||
st.header.stamp = tf3::Time::now();
|
||||
st.header.frame_id = parent_frame;
|
||||
st.child_frame_id = child_frame;
|
||||
st.transform.translation.x = x;
|
||||
st.transform.translation.y = y;
|
||||
st.transform.translation.z = z;
|
||||
st.transform.rotation.x = qx;
|
||||
st.transform.rotation.y = qy;
|
||||
st.transform.rotation.z = qz;
|
||||
st.transform.rotation.w = qw;
|
||||
|
||||
return tf->setTransform(st, "move_base_main(static)", true /*is_static*/);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (set_static_transform("map", "odom", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
|
||||
robot::log_info("[%s:%d]\n Static transform set: map -> odom", __FILE__, __LINE__);
|
||||
} else {
|
||||
robot::log_error("[%s:%d]\n Failed to set static transform: map -> odom", __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
if (set_static_transform("odom", "base_footprint", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
|
||||
robot::log_info("[%s:%d]\n Static transform set: odom -> base_footprint", __FILE__, __LINE__);
|
||||
} else {
|
||||
robot::log_error("[%s:%d]\n Failed to set static transform: odom -> base_footprint", __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
if (set_static_transform("base_footprint", "base_link", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
|
||||
robot::log_info("[%s:%d]\n Static transform set: base_footprint -> base_link", __FILE__, __LINE__);
|
||||
} else {
|
||||
robot::log_error("[%s:%d]\n Failed to set static transform: base_footprint -> base_link", __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
robot::log_info("[%s:%d]\n Loading MoveBase library...", __FILE__, __LINE__);
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath("MoveBase");
|
||||
auto create_plugin = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>(
|
||||
path_file_so,
|
||||
"MoveBase", boost::dll::load_mode::append_decorations);
|
||||
|
||||
robot::log_info("[%s:%d]\n Creating MoveBase instance...", __FILE__, __LINE__);
|
||||
robot::move_base_core::BaseNavigation::Ptr nav_ptr = create_plugin();
|
||||
|
||||
if (nav_ptr == nullptr) {
|
||||
robot::log_error("[%s:%d]\n Error: Failed to create navigation", __FILE__, __LINE__);
|
||||
return 1;
|
||||
}
|
||||
|
||||
robot::log_info("[%s:%d]\n Navigation created, initializing...", __FILE__, __LINE__);
|
||||
nav_ptr->initialize(tf);
|
||||
robot::log_info("[%s:%d]\n Navigation initialized successfully", __FILE__, __LINE__);
|
||||
|
||||
std::cout << "Move Base Main Function :" << robot::Time::now().toSec() << std::endl;
|
||||
// Explicitly reset before create_plugin goes out of scope to ensure proper cleanup order
|
||||
robot::log_info("[%s:%d]\n Cleaning up...", __FILE__, __LINE__);
|
||||
nav_ptr.reset();
|
||||
robot::log_info("[%s:%d]\n Cleanup complete", __FILE__, __LINE__);
|
||||
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
robot::log_error("[%s:%d]\n Exception: %s", __FILE__, __LINE__, e.what());
|
||||
return 1;
|
||||
} catch (...) {
|
||||
robot::log_error("[%s:%d]\n Unknown exception occurred", __FILE__, __LINE__);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,632 +0,0 @@
|
||||
#include <move_base/simple_action_server.h>
|
||||
|
||||
namespace move_base
|
||||
{
|
||||
|
||||
// Constructor
|
||||
template<class ActionSpec>
|
||||
SimpleActionServer<ActionSpec>::SimpleActionServer(const std::string& name,
|
||||
ExecuteCallback execute_callback,
|
||||
bool auto_start)
|
||||
: name_(name),
|
||||
execute_callback_(execute_callback),
|
||||
active_(false),
|
||||
preempt_requested_(false),
|
||||
new_goal_available_(false),
|
||||
goal_(nullptr),
|
||||
status_publish_rate_(10.0)
|
||||
{
|
||||
// Initialize status
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::PENDING;
|
||||
current_status_.goal_id.stamp = robot::Time::now();
|
||||
current_status_.goal_id.id = "";
|
||||
current_status_.text = "";
|
||||
|
||||
if (auto_start)
|
||||
{
|
||||
start();
|
||||
}
|
||||
|
||||
robot::log_info("[SimpleActionServer] Initialized action server: %s", name_.c_str());
|
||||
}
|
||||
|
||||
// Destructor
|
||||
template<class ActionSpec>
|
||||
SimpleActionServer<ActionSpec>::~SimpleActionServer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
// Start the action server
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::start()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
if (!active_)
|
||||
{
|
||||
active_ = true;
|
||||
// Start status publishing thread
|
||||
status_thread_ = boost::thread(boost::bind(&SimpleActionServer::statusPublishThread, this));
|
||||
robot::log_info("[SimpleActionServer] Started action server: %s", name_.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the action server
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::stop()
|
||||
{
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
if (active_)
|
||||
{
|
||||
active_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Notify all waiting threads
|
||||
goal_condition_.notify_all();
|
||||
|
||||
if (status_thread_.joinable())
|
||||
{
|
||||
status_thread_.join();
|
||||
}
|
||||
|
||||
if (execute_thread_.joinable())
|
||||
{
|
||||
execute_thread_.join();
|
||||
}
|
||||
|
||||
robot::log_info("[SimpleActionServer] Stopped action server: %s", name_.c_str());
|
||||
}
|
||||
|
||||
// Set callback for goal messages
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setGoalCallback(GoalCallback callback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
goal_callback_ = callback;
|
||||
}
|
||||
|
||||
// Set callback for cancel messages
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setCancelCallback(CancelCallback callback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
cancel_callback_ = callback;
|
||||
}
|
||||
|
||||
// Set callback for feedback publishing
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setFeedbackCallback(FeedbackCallback callback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
feedback_callback_ = callback;
|
||||
}
|
||||
|
||||
// Set callback for result publishing
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setResultCallback(ResultCallback callback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
result_callback_ = callback;
|
||||
}
|
||||
|
||||
// Set callback for status publishing
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setStatusCallback(StatusCallback callback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
status_callback_ = callback;
|
||||
}
|
||||
|
||||
// Set status publish rate
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setStatusPublishRate(double rate)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
status_publish_rate_ = rate;
|
||||
}
|
||||
|
||||
// Process an incoming goal message
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::processGoal(const ActionGoalConstPtr& goal_msg)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
if (!active_)
|
||||
{
|
||||
robot::log_warning("[SimpleActionServer] Received goal but server is not active");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we should accept this goal
|
||||
bool accept_goal = false;
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::PENDING ||
|
||||
current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
|
||||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
|
||||
{
|
||||
// Check if this is a new goal (different ID)
|
||||
if (goal_msg->goal_id.id != current_goal_id_.id ||
|
||||
goal_msg->goal_id.stamp != current_goal_id_.stamp)
|
||||
{
|
||||
// If we have an active goal, preempt it
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
|
||||
{
|
||||
preempt_requested_ = true;
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTING;
|
||||
robot::log_info("[SimpleActionServer] Preempting current goal for new goal");
|
||||
}
|
||||
|
||||
accept_goal = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// No active goal, accept this one
|
||||
accept_goal = true;
|
||||
}
|
||||
|
||||
if (accept_goal)
|
||||
{
|
||||
// Store the new goal
|
||||
goal_ = boost::make_shared<Goal>(goal_msg->goal);
|
||||
current_goal_id_ = goal_msg->goal_id;
|
||||
new_goal_available_ = true;
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::PENDING;
|
||||
current_status_.goal_id = current_goal_id_;
|
||||
current_status_.text = "";
|
||||
|
||||
robot::log_info("[SimpleActionServer] Received new goal, ID: %s", current_goal_id_.id.c_str());
|
||||
|
||||
// Notify waiting threads
|
||||
goal_condition_.notify_one();
|
||||
|
||||
// Start execute thread if not already running
|
||||
if (execute_callback_)
|
||||
{
|
||||
if (!execute_thread_.joinable())
|
||||
{
|
||||
execute_thread_ = boost::thread(boost::bind(&SimpleActionServer::executeGoal, this));
|
||||
}
|
||||
}
|
||||
|
||||
// Call goal callback if set
|
||||
if (goal_callback_)
|
||||
{
|
||||
goal_callback_(goal_msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process an incoming cancel message
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::processCancel(const robot_actionlib_msgs::GoalIDConstPtr& cancel_msg)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::processCancel] ===== ENTRY =====");
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel message ID: '%s'", cancel_msg->id.c_str());
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel message stamp: %ld.%09ld",
|
||||
cancel_msg->stamp.sec, cancel_msg->stamp.nsec);
|
||||
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
robot::log_info("[SimpleActionServer::processCancel] Current goal ID: '%s'", current_goal_id_.id.c_str());
|
||||
robot::log_info("[SimpleActionServer::processCancel] Current goal stamp: %ld.%09ld",
|
||||
current_goal_id_.stamp.sec, current_goal_id_.stamp.nsec);
|
||||
robot::log_info("[SimpleActionServer::processCancel] Current status: %d", current_status_.status);
|
||||
|
||||
// Check if this cancel request is for the current goal
|
||||
bool should_cancel = false;
|
||||
bool is_empty_id = (cancel_msg->id == "");
|
||||
bool is_matching_id = (cancel_msg->id == current_goal_id_.id);
|
||||
bool is_matching_stamp = (cancel_msg->stamp == current_goal_id_.stamp);
|
||||
|
||||
robot::log_debug("[SimpleActionServer::processCancel] Cancel check: empty_id=%s, matching_id=%s, matching_stamp=%s",
|
||||
is_empty_id ? "true" : "false",
|
||||
is_matching_id ? "true" : "false",
|
||||
is_matching_stamp ? "true" : "false");
|
||||
|
||||
if (is_empty_id || (is_matching_id && is_matching_stamp))
|
||||
{
|
||||
should_cancel = true;
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel request matches current goal - will cancel");
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::processCancel] Goal is ACTIVE - setting preemption");
|
||||
preempt_requested_ = true;
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTING;
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel requested for goal ID: %s", current_goal_id_.id.c_str());
|
||||
robot::log_info("[SimpleActionServer::processCancel] Status changed to PREEMPTING");
|
||||
}
|
||||
else if (current_status_.status == robot_actionlib_msgs::GoalStatus::PENDING)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::processCancel] Goal is PENDING - rejecting it");
|
||||
// Goal hasn't started yet, just reject it
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::REJECTED;
|
||||
current_status_.text = "Goal cancelled before execution";
|
||||
goal_.reset();
|
||||
new_goal_available_ = false;
|
||||
robot::log_info("[SimpleActionServer::processCancel] Goal cancelled before execution");
|
||||
robot::log_info("[SimpleActionServer::processCancel] Status changed to REJECTED");
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::processCancel] Goal status is %d - no action needed", current_status_.status);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel request does NOT match current goal - ignoring");
|
||||
robot::log_info("[SimpleActionServer::processCancel] Cancel ID '%s' != Current ID '%s'",
|
||||
cancel_msg->id.c_str(), current_goal_id_.id.c_str());
|
||||
}
|
||||
|
||||
// Call cancel callback if set
|
||||
robot::log_debug("[SimpleActionServer::processCancel] Checking cancel_callback_: %s",
|
||||
cancel_callback_ ? "set" : "null");
|
||||
if (cancel_callback_)
|
||||
{
|
||||
robot::log_debug("[SimpleActionServer::processCancel] Calling cancel_callback_...");
|
||||
try
|
||||
{
|
||||
cancel_callback_(cancel_msg);
|
||||
robot::log_debug("[SimpleActionServer::processCancel] cancel_callback_ executed successfully");
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
robot::log_error("[SimpleActionServer::processCancel] EXCEPTION in cancel_callback_: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
robot::log_info("[SimpleActionServer::processCancel] ===== EXIT =====");
|
||||
}
|
||||
|
||||
// Check if a new goal is available
|
||||
template<class ActionSpec>
|
||||
bool SimpleActionServer<ActionSpec>::isNewGoalAvailable()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
return new_goal_available_;
|
||||
}
|
||||
|
||||
// Check if preemption has been requested
|
||||
template<class ActionSpec>
|
||||
bool SimpleActionServer<ActionSpec>::isPreemptRequested()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
return preempt_requested_;
|
||||
}
|
||||
|
||||
// Accept a new goal
|
||||
template<class ActionSpec>
|
||||
typename SimpleActionServer<ActionSpec>::GoalConstPtr SimpleActionServer<ActionSpec>::acceptNewGoal()
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== ENTRY =====");
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
robot::log_debug("[SimpleActionServer::acceptNewGoal] new_goal_available_: %s",
|
||||
new_goal_available_ ? "true" : "false");
|
||||
robot::log_debug("[SimpleActionServer::acceptNewGoal] goal_ is %s",
|
||||
goal_ ? "valid" : "null");
|
||||
|
||||
if (!new_goal_available_)
|
||||
{
|
||||
robot::log_warning("[SimpleActionServer::acceptNewGoal] No new goal available - returning null");
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== EXIT (null) =====");
|
||||
return GoalConstPtr();
|
||||
}
|
||||
|
||||
// Accept the new goal
|
||||
GoalConstPtr new_goal = goal_;
|
||||
goal_.reset();
|
||||
new_goal_available_ = false;
|
||||
preempt_requested_ = false;
|
||||
|
||||
// Update status
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::ACTIVE;
|
||||
current_status_.goal_id = current_goal_id_;
|
||||
current_status_.text = "";
|
||||
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal accepted successfully");
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal ID: %s", current_goal_id_.id.c_str());
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] Status changed to ACTIVE");
|
||||
if (new_goal)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal position: x=%.3f, y=%.3f",
|
||||
new_goal->target_pose.pose.position.x,
|
||||
new_goal->target_pose.pose.position.y);
|
||||
}
|
||||
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== EXIT (success) =====");
|
||||
return new_goal;
|
||||
}
|
||||
|
||||
// Set the action as succeeded
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setSucceeded(const Result& result, const std::string& text)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
|
||||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
|
||||
{
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::SUCCEEDED;
|
||||
current_status_.text = text;
|
||||
|
||||
// Create and publish result
|
||||
ActionResultPtr action_result = boost::make_shared<ActionResult>();
|
||||
action_result->header.stamp = robot::Time::now();
|
||||
action_result->status = current_status_;
|
||||
action_result->result = result;
|
||||
|
||||
// Call result callback if set
|
||||
if (result_callback_)
|
||||
{
|
||||
result_callback_(action_result);
|
||||
}
|
||||
|
||||
// Clear goal
|
||||
goal_.reset();
|
||||
new_goal_available_ = false;
|
||||
preempt_requested_ = false;
|
||||
|
||||
robot::log_info("[SimpleActionServer] Goal succeeded: %s", text.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Set the action as aborted
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setAborted(const Result& result, const std::string& text)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
|
||||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
|
||||
{
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::ABORTED;
|
||||
current_status_.text = text;
|
||||
|
||||
// Create and publish result
|
||||
ActionResultPtr action_result = boost::make_shared<ActionResult>();
|
||||
action_result->header.stamp = robot::Time::now();
|
||||
action_result->status = current_status_;
|
||||
action_result->result = result;
|
||||
|
||||
// Call result callback if set
|
||||
if (result_callback_)
|
||||
{
|
||||
result_callback_(action_result);
|
||||
}
|
||||
|
||||
// Clear goal
|
||||
goal_.reset();
|
||||
new_goal_available_ = false;
|
||||
preempt_requested_ = false;
|
||||
|
||||
robot::log_warning("[SimpleActionServer] Goal aborted: %s", text.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Set the action as preempted
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::setPreempted(const Result& result, const std::string& text)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
|
||||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
|
||||
{
|
||||
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTED;
|
||||
current_status_.text = text;
|
||||
|
||||
// Create and publish result
|
||||
ActionResultPtr action_result = boost::make_shared<ActionResult>();
|
||||
action_result->header.stamp = robot::Time::now();
|
||||
action_result->status = current_status_;
|
||||
action_result->result = result;
|
||||
|
||||
// Call result callback if set
|
||||
if (result_callback_)
|
||||
{
|
||||
result_callback_(action_result);
|
||||
}
|
||||
|
||||
// Clear goal
|
||||
goal_.reset();
|
||||
new_goal_available_ = false;
|
||||
preempt_requested_ = false;
|
||||
|
||||
robot::log_info("[SimpleActionServer] Goal preempted: %s", text.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Publish feedback
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::publishFeedback(const Feedback& feedback)
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
|
||||
{
|
||||
ActionFeedbackPtr action_feedback = boost::make_shared<ActionFeedback>();
|
||||
action_feedback->header.stamp = robot::Time::now();
|
||||
action_feedback->status = current_status_;
|
||||
action_feedback->feedback = feedback;
|
||||
|
||||
// Call feedback callback if set
|
||||
if (feedback_callback_)
|
||||
{
|
||||
feedback_callback_(action_feedback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current goal
|
||||
template<class ActionSpec>
|
||||
typename SimpleActionServer<ActionSpec>::GoalConstPtr SimpleActionServer<ActionSpec>::getCurrentGoal()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
return goal_;
|
||||
}
|
||||
|
||||
// Get the current status
|
||||
template<class ActionSpec>
|
||||
robot_actionlib_msgs::GoalStatus SimpleActionServer<ActionSpec>::getCurrentStatus()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
return current_status_;
|
||||
}
|
||||
|
||||
// Check if the server is active
|
||||
template<class ActionSpec>
|
||||
bool SimpleActionServer<ActionSpec>::isActive()
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
return active_;
|
||||
}
|
||||
|
||||
// Get the action name
|
||||
template<class ActionSpec>
|
||||
std::string SimpleActionServer<ActionSpec>::getName() const
|
||||
{
|
||||
return name_;
|
||||
}
|
||||
|
||||
// Execute the goal in a separate thread
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::executeGoal()
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::executeGoal] ===== THREAD STARTED =====");
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Action server name: %s", name_.c_str());
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] execute_callback_ is %s",
|
||||
execute_callback_ ? "set" : "null");
|
||||
|
||||
// Continuously process goals
|
||||
while (active_)
|
||||
{
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] Waiting for new goal...");
|
||||
GoalConstPtr goal_to_execute;
|
||||
|
||||
// Wait for a new goal to be available
|
||||
{
|
||||
boost::unique_lock<boost::mutex> lock(state_mutex_);
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] Mutex lock acquired in executeGoal");
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] active_=%s, new_goal_available_=%s",
|
||||
active_ ? "true" : "false",
|
||||
new_goal_available_ ? "true" : "false");
|
||||
|
||||
// Wait until a new goal is available or server is stopped
|
||||
while (active_ && !new_goal_available_)
|
||||
{
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] Waiting on condition variable...");
|
||||
goal_condition_.wait(lock);
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] Woke up from condition wait");
|
||||
robot::log_debug("[SimpleActionServer::executeGoal] After wake: active_=%s, new_goal_available_=%s",
|
||||
active_ ? "true" : "false",
|
||||
new_goal_available_ ? "true" : "false");
|
||||
}
|
||||
|
||||
if (!active_)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Server is not active - exiting thread");
|
||||
break;
|
||||
}
|
||||
|
||||
// Accept the new goal
|
||||
if (new_goal_available_)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::executeGoal] New goal available - accepting it...");
|
||||
|
||||
// Release lock before calling acceptNewGoal() to avoid deadlock
|
||||
// (acceptNewGoal() will acquire its own lock)
|
||||
lock.unlock();
|
||||
|
||||
goal_to_execute = acceptNewGoal();
|
||||
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Goal accepted: %s",
|
||||
goal_to_execute ? "valid" : "null");
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning("[SimpleActionServer::executeGoal] Woke up but new_goal_available_ is false!");
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the goal callback
|
||||
if (goal_to_execute)
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Executing goal callback...");
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Goal position: x=%.3f, y=%.3f",
|
||||
goal_to_execute->target_pose.pose.position.x,
|
||||
goal_to_execute->target_pose.pose.position.y);
|
||||
|
||||
if (execute_callback_)
|
||||
{
|
||||
try
|
||||
{
|
||||
robot::log_info("[SimpleActionServer::executeGoal] Calling execute_callback_...");
|
||||
execute_callback_(goal_to_execute);
|
||||
robot::log_info("[SimpleActionServer::executeGoal] execute_callback_ completed");
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
robot::log_error("[SimpleActionServer::executeGoal] EXCEPTION in execute_callback_: %s", e.what());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_error("[SimpleActionServer::executeGoal] execute_callback_ is null - cannot execute goal!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning("[SimpleActionServer::executeGoal] goal_to_execute is null - skipping execution");
|
||||
}
|
||||
}
|
||||
|
||||
robot::log_info("[SimpleActionServer::executeGoal] ===== THREAD EXITING =====");
|
||||
}
|
||||
|
||||
// Thread function to publish status periodically
|
||||
template<class ActionSpec>
|
||||
void SimpleActionServer<ActionSpec>::statusPublishThread()
|
||||
{
|
||||
double rate = status_publish_rate_;
|
||||
robot::Duration sleep_duration(1.0 / rate);
|
||||
|
||||
while (active_)
|
||||
{
|
||||
{
|
||||
boost::lock_guard<boost::mutex> lock(state_mutex_);
|
||||
|
||||
// Create status array
|
||||
robot_actionlib_msgs::GoalStatusArrayPtr status_array =
|
||||
boost::make_shared<robot_actionlib_msgs::GoalStatusArray>();
|
||||
status_array->header.stamp = robot::Time::now();
|
||||
status_array->status_list.clear();
|
||||
|
||||
if (current_status_.status != robot_actionlib_msgs::GoalStatus::PENDING ||
|
||||
!current_goal_id_.id.empty())
|
||||
{
|
||||
status_array->status_list.push_back(current_status_);
|
||||
}
|
||||
|
||||
// Call status callback if set
|
||||
if (status_callback_)
|
||||
{
|
||||
status_callback_(status_array);
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep
|
||||
robot::Time::sleepUntil(robot::Time::now() + sleep_duration);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace move_base
|
||||
|
||||
// Explicit template instantiation for MoveBaseAction
|
||||
// This is required because template method definitions are in .cpp file
|
||||
template class move_base::SimpleActionServer<robot_move_base_msgs::MoveBaseAction>;
|
||||
|
||||
Reference in New Issue
Block a user