26 Commits

Author SHA1 Message Date
clhchan 2a066ab48e chore(agv_pro_navigation2): clean nav launch and example script 2026-06-01 10:44:38 +08:00
clhchan 8d03de9ad6 docs: update navigation parameter comments 2026-05-26 11:27:06 +08:00
clhchan f966a123e4 feat: improve AGV navigation performance 2026-05-26 11:15:41 +08:00
X-lanni 39cb5cf26f Merge pull request #11 from elephantrobotics/humble-dev
fix(agv_pro_bringup): add launch with RViz condition
2026-04-09 18:01:26 +08:00
X-lanni be405bb64d fix(agv_pro_bringup): add launch with RViz condition 2026-04-08 19:02:32 +08:00
X-lanni 30895501ed Merge pull request #10 from elephantrobotics/humble-dev
feat(agv_pro_base,agv_pro_msgs): add LED color and mode services with…
2026-03-04 19:01:11 +08:00
X-lanni fcb8987589 feat(agv_pro_base,agv_pro_msgs): add LED color and mode services with driver support 2026-03-04 18:58:47 +08:00
X-lanni 021fb5ba1a Merge pull request #9 from elephantrobotics/humble-dev
fix(livox_ros_driver2,agv_pro_bringup): cleanup ROS2 launch files and…
2026-01-20 18:45:21 +08:00
X-lanni 98b9fb2122 fix(livox_ros_driver2,agv_pro_bringup): cleanup ROS2 launch files and improve lidar bringup 2026-01-20 18:44:15 +08:00
X-lanni f0c1d0b36d Merge pull request #8 from elephantrobotics/humble-dev
fix(unitree_lidar_ros2): update CMakeLists.txt
2026-01-14 17:15:53 +08:00
X-lanni 3273b4ba8c fix(unitree_lidar_ros2): update CMakeLists.txt 2026-01-14 17:14:52 +08:00
X-lanni b4ecf2d46b Merge pull request #7 from elephantrobotics/humble-dev
fix(livox_ros_driver2): add package.xml
2026-01-14 14:53:22 +08:00
X-lanni a5b118ad79 fix(livox_ros_driver2): add package.xml 2026-01-14 14:51:04 +08:00
X-lanni 2fa19af554 Merge pull request #6 from elephantrobotics/humble-dev
fix(livox_ros_driver2): update CMakeLists.txt
2026-01-14 14:43:06 +08:00
X-lanni 1ace9dd1e3 fix(livox_ros_driver2): update CMakeLists.txt 2026-01-14 14:42:12 +08:00
X-lanni 097bf4f2ca Merge pull request #5 from elephantrobotics/humble-slam
Humble slam
2026-01-13 19:15:10 +08:00
X-lanni ddef31d11a feat(slam): add lidar SLAM and pointcloud processing packages 2026-01-13 19:12:25 +08:00
X-lanni dcb52622eb feat(agv_pro_bringup): add multi-lidar support and drivers 2026-01-13 19:12:09 +08:00
X-lanni b50a0c4496 Merge pull request #3 from elephantrobotics/humble-dev
feat(agv_pro_msgs): add SetDigitalOutput and GetDigitalInput srv defi…
2025-11-06 19:15:15 +08:00
X-lanni 305373ed09 feat(agv_pro_msgs): add SetDigitalOutput and GetDigitalInput srv definitions 2025-11-06 18:24:31 +08:00
X-lanni 7348751c89 Merge pull request #2 from elephantrobotics/humble-imu
perf(nav2_params): Optimize nav2 navigation parameters
2025-09-30 17:54:26 +08:00
X-lanni 530a53641e perf(nav2_params): Optimize nav2 navigation parameters 2025-09-30 17:52:14 +08:00
X-lanni 959f2ac4ee Merge pull request #1 from elephantrobotics/humble-imu
Add IMU support, auto recharge, RViz tool, and rtabmap demos
2025-09-29 19:09:08 +08:00
X-lanni cf17bb899b feat(rtabmap_ros): Add demo configurations, launch files, and navigation parameters for agvpro 2025-09-28 19:18:59 +08:00
X-lanni 049d3995ba feat(navigation2): add RViz charger tool 2025-09-23 10:11:30 +08:00
X-lanni c6dbf7084e feat(agv_pro_autocharge): Added automatic recharge function code 2025-09-19 13:45:59 +08:00
303 changed files with 63370 additions and 144 deletions
+17
View File
@@ -0,0 +1,17 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 21
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 1
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
+8
View File
@@ -0,0 +1,8 @@
build
Log/*.png
Log/*.txt
Log/*.csv
Log/*.pdf
.vscode/c_cpp_properties.json
.vscode/settings.json
PCD/*.pcd
+4
View File
@@ -0,0 +1,4 @@
[submodule "include/ikd-Tree"]
path = include/ikd-Tree
url = https://github.com/hku-mars/ikd-Tree.git
branch = fast_lio
+128
View File
@@ -0,0 +1,128 @@
cmake_minimum_required(VERSION 3.8)
project(fast_lio)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
ADD_COMPILE_OPTIONS(-std=c++17)
ADD_COMPILE_OPTIONS(-std=c++17)
set(CMAKE_CXX_FLAGS "-std=c++17 -O3")
add_definitions(-DROOT_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/\")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fexceptions")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -pthread -std=c++0x -std=c++14 -fexceptions")
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
message("Current CPU archtecture: ${CMAKE_SYSTEM_PROCESSOR}")
if(CMAKE_SYSTEM_PROCESSOR MATCHES "(x86)|(X86)|(amd64)|(AMD64)")
include(ProcessorCount)
ProcessorCount(N)
message("Processer number: ${N}")
if(N GREATER 4)
add_definitions(-DMP_EN)
add_definitions(-DMP_PROC_NUM=3)
message("core for MP: 3")
elseif(N GREATER 3)
add_definitions(-DMP_EN)
add_definitions(-DMP_PROC_NUM=2)
message("core for MP: 2")
else()
add_definitions(-DMP_PROC_NUM=1)
endif()
else()
add_definitions(-DMP_PROC_NUM=1)
endif()
find_package(OpenMP QUIET)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
find_package(PythonLibs REQUIRED)
find_path(MATPLOTLIB_CPP_INCLUDE_DIRS "matplotlibcpp.h")
# ROS dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclcpp_components REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(std_msgs REQUIRED)
find_package(std_srvs REQUIRED)
find_package(visualization_msgs REQUIRED)
find_package(pcl_ros REQUIRED)
find_package(pcl_conversions REQUIRED)
find_package(livox_ros_driver2 REQUIRED)
find_package(rosidl_default_generators REQUIRED)
set(dependencies
rclcpp
rclcpp_components
geometry_msgs
nav_msgs
sensor_msgs
std_msgs
std_srvs
visualization_msgs
pcl_ros
pcl_conversions
livox_ros_driver2
)
# Thirdparty libraries
find_package(Eigen3 REQUIRED)
find_package(PCL REQUIRED COMPONENTS common io)
message(Eigen: ${EIGEN3_INCLUDE_DIR})
message(STATUS "PCL: ${PCL_INCLUDE_DIRS}")
set(msg_files
"msg/Pose6D.msg"
)
rosidl_generate_interfaces(${PROJECT_NAME}
${msg_files}
)
ament_export_dependencies(rosidl_default_runtime)
add_executable(fastlio_mapping src/laserMapping.cpp include/ikd-Tree/ikd_Tree.cpp src/preprocess.cpp)
target_include_directories(fastlio_mapping PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
${PCL_INCLUDE_DIRS}
)
target_link_libraries(fastlio_mapping ${PCL_LIBRARIES} ${PYTHON_LIBRARIES} Eigen3::Eigen)
target_include_directories(fastlio_mapping PRIVATE ${PYTHON_INCLUDE_DIRS})
list(APPEND EOL_LIST "foxy" "galactic" "eloquent" "dashing" "crystal")
if($ENV{ROS_DISTRO} IN_LIST EOL_LIST)
# Custommsg to support foxy & galactic
rosidl_target_interfaces(fastlio_mapping
${PROJECT_NAME} "rosidl_typesupport_cpp")
else()
rosidl_get_typesupport_target(cpp_typesupport_target
${PROJECT_NAME} "rosidl_typesupport_cpp")
target_link_libraries(fastlio_mapping ${cpp_typesupport_target})
endif()
ament_target_dependencies(fastlio_mapping ${dependencies})
# ---------------- Install --------------- #
install(TARGETS fastlio_mapping
DESTINATION lib/${PROJECT_NAME}
)
install(
DIRECTORY config launch rviz
DESTINATION share/${PROJECT_NAME}
)
ament_package()
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+135
View File
@@ -0,0 +1,135 @@
clear
close all
Color_red = [0.6350 0.0780 0.1840];
Color_blue = [0 0.4470 0.7410];
Color_orange = [0.8500 0.3250 0.0980];
Color_green = [0.4660 0.6740 0.1880];
Color_lightblue = [0.3010 0.7450 0.9330];
Color_purple = [0.4940 0.1840 0.5560];
Color_yellow = [0.9290 0.6940 0.1250];
fast_lio_ikdtree = csvread("./fast_lio_time_log.csv",1,0);
timestamp_ikd = fast_lio_ikdtree(:,1);
timestamp_ikd = timestamp_ikd - min(timestamp_ikd);
total_time_ikd = fast_lio_ikdtree(:,2)*1e3;
scan_num = fast_lio_ikdtree(:,3);
incremental_time_ikd = fast_lio_ikdtree(:,4)*1e3;
search_time_ikd = fast_lio_ikdtree(:,5)*1e3;
delete_size_ikd = fast_lio_ikdtree(:,6);
delete_time_ikd = fast_lio_ikdtree(:,7) * 1e3;
tree_size_ikd_st = fast_lio_ikdtree(:,8);
tree_size_ikd = fast_lio_ikdtree(:,9);
add_points = fast_lio_ikdtree(:,10);
fast_lio_forest = csvread("fast_lio_time_log.csv",1,0);
fov_check_time_forest = fast_lio_forest(:,5)*1e3;
average_time_forest = fast_lio_forest(:,2)*1e3;
total_time_forest = fast_lio_forest(:,6)*1e3;
incremental_time_forest = fast_lio_forest(:,3)*1e3;
search_time_forest = fast_lio_forest(:,4)*1e3;
timestamp_forest = fast_lio_forest(:,1);
% Use slide window to calculate average
L = 1; % Length of slide window
for i = 1:length(timestamp_ikd)
if (i<L)
average_time_ikd(i) = mean(total_time_ikd(1:i));
else
average_time_ikd(i) = mean(total_time_ikd(i-L+1:i));
end
end
for i = 1:length(timestamp_forest)
if (i<L)
average_time_forest(i) = mean(total_time_forest(1:i));
else
average_time_forest(i) = mean(total_time_forest(i-L+1:i));
end
end
f = figure;
set(gcf,'Position',[80 433 600 640])
tiled_handler = tiledlayout(3,1);
tiled_handler.TileSpacing = 'compact';
tiled_handler.Padding = 'compact';
nexttile;
hold on;
set(gca,'FontSize',12,'FontName','Times New Roman')
plot(timestamp_ikd, average_time_ikd,'-','Color',Color_blue,'LineWidth',1.2);
plot(timestamp_forest, average_time_forest,'--','Color',Color_orange,'LineWidth',1.2);
lg = legend("ikd-Tree", "ikd-Forest",'location',[0.1314 0.8559 0.2650 0.0789],'fontsize',14,'fontname','Times New Roman')
title("Time Performance on FAST-LIO",'FontSize',16,'FontName','Times New Roman')
xlabel("time/s",'FontSize',16,'FontName','Times New Roman')
yl = ylabel("Run Time/ms",'FontSize',15,'Position',[285.7 5.5000 -1]);
xlim([32,390]);
ylim([0,23]);
ax1 = gca;
ax1.YAxis.FontSize = 12;
ax1.XAxis.FontSize = 12;
grid on
box on
% print('./Figures/fastlio_exp_average','-depsc','-r600')
index_ikd = find(search_time_ikd > 0);
search_time_ikd = search_time_ikd(index_ikd);
index_forest = find(search_time_forest > 0);
search_time_forest = search_time_forest(index_forest);
t = nexttile;
hold on;
boxplot_data_ikd = [incremental_time_ikd,total_time_ikd];
boxplot_data_forest = [incremental_time_forest,total_time_forest];
Colors_ikd = [Color_blue;Color_blue;Color_blue];
Colors_forest = [Color_orange;Color_orange;Color_orange];
% xticks([3,8,13])
h_search_ikd = boxplot(search_time_ikd,'Whisker',50,'Positions',1,'Colors',Color_blue,'Widths',0.3);
h_search_forest = boxplot(search_time_forest,'Whisker',50,'Positions',1.5,'Colors',Color_orange,'Widths',0.3);
h_ikd = boxplot(boxplot_data_ikd,'Whisker',50,'Positions',[3,5],'Colors',Color_blue,'Widths',0.3);
h_forest = boxplot(boxplot_data_forest,'Whisker',50,'Positions',[3.5,5.5],'Colors',Color_orange,'Widths',0.3);
ax2 = gca;
ax2.YAxis.Scale = 'log';
xlim([0.5,6.0])
ylim([0.0008,100])
xticks([1.25 3.25 5.25])
xticklabels({'Nearest Search',' Incremental Updates','Total Time'});
yticks([1e-3,1e-2,1e-1,1e0,1e1,1e2])
ax2.YAxis.FontSize = 12;
ax2.XAxis.FontSize = 14.5;
% ax.XAxis.FontWeight = 'bold';
ylabel('Run Time/ms','FontSize',14,'FontName','Times New Roman')
box_vars = [findall(h_search_ikd,'Tag','Box');findall(h_ikd,'Tag','Box');findall(h_search_forest,'Tag','Box');findall(h_forest,'Tag','Box')];
for j=1:length(box_vars)
if (j<=3)
Color = Color_blue;
else
Color = Color_orange;
end
patch(get(box_vars(j),'XData'),get(box_vars(j),'YData'),Color,'FaceAlpha',0.25,'EdgeColor',Color);
end
Lg = legend(box_vars([1,4]), {'ikd-Tree','ikd-Forest'},'Location',[0.6707 0.4305 0.265 0.07891],'fontsize',14,'fontname','Times New Roman');
grid on
set(gca,'YMinorGrid','off')
nexttile;
hold on;
grid on;
box on;
set(gca,'FontSize',12,'FontName','Times New Roman')
plot(timestamp_ikd, alpha_bal_ikd,'-','Color',Color_blue,'LineWidth',1.2);
plot(timestamp_ikd, alpha_del_ikd,'--','Color',Color_orange, 'LineWidth', 1.2);
plot(timestamp_ikd, 0.6*ones(size(alpha_bal_ikd)), ':','Color','black','LineWidth',1.2);
lg = legend("\alpha_{bal}", "\alpha_{del}",'location',[0.7871 0.1131 0.1433 0.069],'fontsize',14,'fontname','Times New Roman')
title("Re-balancing Criterion",'FontSize',16,'FontName','Times New Roman')
xlabel("time/s",'FontSize',16,'FontName','Times New Roman')
yl = ylabel("\alpha",'FontSize',15, 'Position',[285.7 0.4250 -1])
xlim([32,390]);
ylim([0,0.85]);
ax3 = gca;
ax3.YAxis.FontSize = 12;
ax3.XAxis.FontSize = 12;
% print('./Figures/fastlio_exp_combine','-depsc','-r1200')
% exportgraphics(f,'./Figures/fastlio_exp_combine_1.pdf','ContentType','vector')
+1
View File
@@ -0,0 +1 @@
Here saved the debug records which can be drew by the ../Log/plot.py. The record function can be found frm the MACRO: DEBUG_FILE_DIR(name) in common_lib.h.
+94
View File
@@ -0,0 +1,94 @@
# import matplotlib
# matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
#######for ikfom
fig, axs = plt.subplots(4,2)
lab_pre = ['', 'pre-x', 'pre-y', 'pre-z']
lab_out = ['', 'out-x', 'out-y', 'out-z']
plot_ind = range(7,10)
a_pre=np.loadtxt('mat_pre.txt')
a_out=np.loadtxt('mat_out.txt')
time=a_pre[:,0]
axs[0,0].set_title('Attitude')
axs[1,0].set_title('Translation')
axs[2,0].set_title('Extrins-R')
axs[3,0].set_title('Extrins-T')
axs[0,1].set_title('Velocity')
axs[1,1].set_title('bg')
axs[2,1].set_title('ba')
axs[3,1].set_title('Gravity')
for i in range(1,4):
for j in range(8):
axs[j%4, j/4].plot(time, a_pre[:,i+j*3],'.-', label=lab_pre[i])
axs[j%4, j/4].plot(time, a_out[:,i+j*3],'.-', label=lab_out[i])
for j in range(8):
# axs[j].set_xlim(386,389)
axs[j%4, j/4].grid()
axs[j%4, j/4].legend()
plt.grid()
#######for ikfom#######
#### Draw IMU data
# fig, axs = plt.subplots(2)
# imu=np.loadtxt('imu.txt')
# time=imu[:,0]
# axs[0].set_title('Gyroscope')
# axs[1].set_title('Accelerameter')
# lab_1 = ['gyr-x', 'gyr-y', 'gyr-z']
# lab_2 = ['acc-x', 'acc-y', 'acc-z']
# for i in range(3):
# # if i==1:
# axs[0].plot(time, imu[:,i+1],'.-', label=lab_1[i])
# axs[1].plot(time, imu[:,i+4],'.-', label=lab_2[i])
# for i in range(2):
# # axs[i].set_xlim(386,389)
# axs[i].grid()
# axs[i].legend()
# plt.grid()
# #### Draw time calculation
# plt.figure(3)
# fig = plt.figure()
# font1 = {'family' : 'Times New Roman',
# 'weight' : 'normal',
# 'size' : 12,
# }
# c="red"
# a_out1=np.loadtxt('Log/mat_out_time_indoor1.txt')
# a_out2=np.loadtxt('Log/mat_out_time_indoor2.txt')
# a_out3=np.loadtxt('Log/mat_out_time_outdoor.txt')
# # n = a_out[:,1].size
# # time_mean = a_out[:,1].mean()
# # time_se = a_out[:,1].std() / np.sqrt(n)
# # time_err = a_out[:,1] - time_mean
# # feat_mean = a_out[:,2].mean()
# # feat_err = a_out[:,2] - feat_mean
# # feat_se = a_out[:,2].std() / np.sqrt(n)
# ax1 = fig.add_subplot(111)
# ax1.set_ylabel('Effective Feature Numbers',font1)
# ax1.boxplot(a_out1[:,2], showfliers=False, positions=[0.9])
# ax1.boxplot(a_out2[:,2], showfliers=False, positions=[1.9])
# ax1.boxplot(a_out3[:,2], showfliers=False, positions=[2.9])
# ax1.set_ylim([0, 3000])
# ax2 = ax1.twinx()
# ax2.spines['right'].set_color('red')
# ax2.set_ylabel('Compute Time (ms)',font1)
# ax2.yaxis.label.set_color('red')
# ax2.tick_params(axis='y', colors='red')
# ax2.boxplot(a_out1[:,1]*1000, showfliers=False, positions=[1.1],boxprops=dict(color=c),capprops=dict(color=c),whiskerprops=dict(color=c))
# ax2.boxplot(a_out2[:,1]*1000, showfliers=False, positions=[2.1],boxprops=dict(color=c),capprops=dict(color=c),whiskerprops=dict(color=c))
# ax2.boxplot(a_out3[:,1]*1000, showfliers=False, positions=[3.1],boxprops=dict(color=c),capprops=dict(color=c),whiskerprops=dict(color=c))
# ax2.set_xlim([0.5, 3.5])
# ax2.set_ylim([0, 100])
# plt.xticks([1,2,3], ('Outdoor Scene', 'Indoor Scene 1', 'Indoor Scene 2'))
# # # print(time_se)
# # # print(a_out3[:,2])
# plt.grid()
# plt.savefig("time.pdf", dpi=1200)
plt.show()
+1
View File
@@ -0,0 +1 @@
1
+199
View File
@@ -0,0 +1,199 @@
> ROS2 Fork repo maintainer: [Ericsiii](https://github.com/Ericsii)
## Related Works and Extended Application
**SLAM:**
1. [ikd-Tree](https://github.com/hku-mars/ikd-Tree): A state-of-art dynamic KD-Tree for 3D kNN search.
2. [R2LIVE](https://github.com/hku-mars/r2live): A high-precision LiDAR-inertial-Vision fusion work using FAST-LIO as LiDAR-inertial front-end.
3. [LI_Init](https://github.com/hku-mars/LiDAR_IMU_Init): A robust, real-time LiDAR-IMU extrinsic initialization and synchronization package..
4. [FAST-LIO-LOCALIZATION](https://github.com/HViktorTsoi/FAST_LIO_LOCALIZATION): The integration of FAST-LIO with **Re-localization** function module.
**Control and Plan:**
1. [IKFOM](https://github.com/hku-mars/IKFoM): A Toolbox for fast and high-precision on-manifold Kalman filter.
2. [UAV Avoiding Dynamic Obstacles](https://github.com/hku-mars/dyn_small_obs_avoidance): One of the implementation of FAST-LIO in robot's planning.
3. [UGV Demo](https://www.youtube.com/watch?v=wikgrQbE6Cs): Model Predictive Control for Trajectory Tracking on Differentiable Manifolds.
4. [Bubble Planner](https://arxiv.org/abs/2202.12177): Planning High-speed Smooth Quadrotor Trajectories using Receding Corridors.
<!-- 10. [**FAST-LIVO**](https://github.com/hku-mars/FAST-LIVO): Fast and Tightly-coupled Sparse-Direct LiDAR-Inertial-Visual Odometry. -->
## FAST-LIO
**FAST-LIO** (Fast LiDAR-Inertial Odometry) is a computationally efficient and robust LiDAR-inertial odometry package. It fuses LiDAR feature points with IMU data using a tightly-coupled iterated extended Kalman filter to allow robust navigation in fast-motion, noisy or cluttered environments where degeneration occurs. Our package address many key issues:
1. Fast iterated Kalman filter for odometry optimization;
2. Automaticaly initialized at most steady environments;
3. Parallel KD-Tree Search to decrease the computation;
## FAST-LIO 2.0 (2021-07-05 Update)
<!-- ![image](https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/real_experiment2.gif) -->
<!-- [![Watch the video](https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/real_exp_2.png)](https://youtu.be/2OvjGnxszf8) -->
<div align="left">
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/real_experiment2.gif" width=49.6% />
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/ulhkwh_fastlio.gif" width = 49.6% >
</div>
**Related video:** [FAST-LIO2](https://youtu.be/2OvjGnxszf8), [FAST-LIO1](https://youtu.be/iYCY6T79oNU)
**Pipeline:**
<div align="center">
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/overview_fastlio2.svg" width=99% />
</div>
**New Features:**
1. Incremental mapping using [ikd-Tree](https://github.com/hku-mars/ikd-Tree), achieve faster speed and over 100Hz LiDAR rate.
2. Direct odometry (scan to map) on Raw LiDAR points (feature extraction can be disabled), achieving better accuracy.
3. Since no requirements for feature extraction, FAST-LIO2 can support many types of LiDAR including spinning (Velodyne, Ouster) and solid-state (Livox Avia, Horizon, MID-70) LiDARs, and can be easily extended to support more LiDARs.
4. Support external IMU.
5. Support ARM-based platforms including Khadas VIM3, Nivida TX2, Raspberry Pi 4B(8G RAM).
**Related papers**:
[FAST-LIO2: Fast Direct LiDAR-inertial Odometry](https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/Fast_LIO_2.pdf)
[FAST-LIO: A Fast, Robust LiDAR-inertial Odometry Package by Tightly-Coupled Iterated Kalman Filter](https://arxiv.org/abs/2010.08196)
**Contributors**
[Wei Xu 徐威](https://github.com/XW-HKU)[Yixi Cai 蔡逸熙](https://github.com/Ecstasy-EC)[Dongjiao He 贺东娇](https://github.com/Joanna-HE)[Fangcheng Zhu 朱方程](https://github.com/zfc-zfc)[Jiarong Lin 林家荣](https://github.com/ziv-lin)[Zheng Liu 刘政](https://github.com/Zale-Liu), [Borong Yuan](https://github.com/borongyuan)
<!-- <div align="center">
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/results/HKU_HW.png" width = 49% >
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/results/HKU_MB_001.png" width = 49% >
</div> -->
## 1. Prerequisites
### 1.1 **Ubuntu** and **ROS**
**Ubuntu >= 20.04**
The **default from apt** PCL and Eigen is enough for FAST-LIO to work normally.
ROS >= Foxy (Recommend to use ROS-Humble). [ROS Installation](https://docs.ros.org/en/humble/Installation.html)
### 1.2. **PCL && Eigen**
PCL >= 1.8, Follow [PCL Installation](https://pointclouds.org/downloads/#linux).
Eigen >= 3.3.4, Follow [Eigen Installation](http://eigen.tuxfamily.org/index.php?title=Main_Page).
### <span id="1.3">1.3. **livox_ros_driver2**</span>
Follow [livox_ros_driver2 Installation](https://github.com/Livox-SDK/livox_ros_driver2).
You can also use the one I modified [livox_ros_driver2](https://github.com/Ericsii/livox_ros_driver2/tree/feature/use-standard-unit)
*Remarks:*
- Since the FAST-LIO must support Livox serials LiDAR firstly, so the **livox_ros_driver** must be installed and **sourced** before run any FAST-LIO launch file.
- How to source? The easiest way is add the line ``` source $Livox_ros_driver_dir$/devel/setup.bash ``` to the end of file ``` ~/.bashrc ```, where ``` $Livox_ros_driver_dir$ ``` is the directory of the livox ros driver workspace (should be the ``` ws_livox ``` directory if you completely followed the livox official document).
## 2. Build
Clone the repository and colcon build:
```bash
cd <ros2_ws>/src # cd into a ros2 workspace folder
git clone https://github.com/Ericsii/FAST_LIO_ROS2.git --recursive
cd ..
rosdep install --from-paths src --ignore-src -y
colcon build --symlink-install
. ./install/setup.bash # use setup.zsh if use zsh
```
- **Remember to source the livox_ros_driver before build (follow [1.3 livox_ros_driver](#1.3))**
- If you want to use a custom build of PCL, add the following line to ~/.bashrc
```export PCL_ROOT={CUSTOM_PCL_PATH}```
## 3. Directly run
Noted:
A. Please make sure the IMU and LiDAR are **Synchronized**, that's important.
B. The warning message "Failed to find match for field 'time'." means the timestamps of each LiDAR points are missed in the rosbag file. That is important for the forward propagation and backwark propagation.
C. We recommend to set the **extrinsic_est_en** to false if the extrinsic is give. As for the extrinsic initiallization, please refer to our recent work: [**Robust Real-time LiDAR-inertial Initialization**](https://github.com/hku-mars/LiDAR_IMU_Init).
### 3.1 Run use ros launch
Connect to your PC to Livox LiDAR by following [Livox-ros-driver2 installation](https://github.com/Livox-SDK/livox_ros_driver2), then
```bash
cd <ros2_ws>
. install/setup.bash # use setup.zsh if use zsh
ros2 launch fast_lio mapping.launch.py config_file:=avia.yaml
```
Change `config_file` parameter to other yaml file under config directory as you need.
Launch livox ros driver. Use MID360 as an example.
```bash
ros2 launch livox_ros_driver2 msg_MID360_launch.py
```
- For livox serials, FAST-LIO only support the data collected by the ``` livox_lidar_msg.launch ``` since only its ``` livox_ros_driver2/CustomMsg ``` data structure produces the timestamp of each LiDAR point which is very important for the motion undistortion. ``` livox_lidar.launch ``` can not produce it right now.
- If you want to change the frame rate, please modify the **publish_freq** parameter in the [livox_lidar_msg.launch](https://github.com/Livox-SDK/livox_ros_driver/blob/master/livox_ros_driver2/launch/livox_lidar_msg.launch) of [Livox-ros-driver](https://github.com/Livox-SDK/livox_ros_driver2) before make the livox_ros_driver pakage.
### 3.2 For Livox serials with external IMU
mapping_avia.launch theratically supports mid-70, mid-40 or other livox serial LiDAR, but need to setup some parameters befor run:
Edit ``` config/avia.yaml ``` to set the below parameters:
1. LiDAR point cloud topic name: ``` lid_topic ```
2. IMU topic name: ``` imu_topic ```
3. Translational extrinsic: ``` extrinsic_T ```
4. Rotational extrinsic: ``` extrinsic_R ``` (only support rotation matrix)
- The extrinsic parameters in FAST-LIO is defined as the LiDAR's pose (position and rotation matrix) in IMU body frame (i.e. the IMU is the base frame). They can be found in the official manual.
- FAST-LIO produces a very simple software time sync for livox LiDAR, set parameter ```time_sync_en``` to ture to turn on. But turn on **ONLY IF external time synchronization is really not possible**, since the software time sync cannot make sure accuracy.
### 3.4 PCD file save
1. Enable `pcd_save.pcd_save_en` in the config file and set the `map_file_path` to the path where the map will be saved.
2. Launch the fastlio2 according to README.
3. Open RQt and switch to `Plugins->Services->Service Caller`. Trigger the service `/map_save`, then the pcd map file will be generated
```pcl_viewer scans.pcd``` can visualize the point clouds.
*Tips for pcl_viewer:*
- change what to visualize/color by pressing keyboard 1,2,3,4,5 when pcl_viewer is running.
```
1 is all random
2 is X values
3 is Y values
4 is Z values
5 is intensity
```
## 4. Rosbag Example
### 4.1 Livox Avia Rosbag
<div align="left">
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/results/HKU_LG_Indoor.png" width=47% />
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/results/HKU_MB_002.png" width = 51% >
Files: Can be downloaded from [google drive](https://drive.google.com/drive/folders/1CGYEJ9-wWjr8INyan6q1BZz_5VtGB-fP?usp=sharing)**!!!This ros1 bag should be convert to ros2!!!**
Run:
```bash
ros2 launch fast_lio mapping.launch.py config_path:=<path_to_your_config_file>
ros2 bag play <your_bag_dir>
```
### 4.2 Velodyne HDL-32E Rosbag
**NCLT Dataset**: Original bin file can be found [here](http://robots.engin.umich.edu/nclt/).
We produce [Rosbag Files](https://drive.google.com/drive/folders/1VBK5idI1oyW0GC_I_Hxh63aqam3nocNK?usp=sharing) and [a python script](https://drive.google.com/file/d/1leh7DxbHx29DyS1NJkvEfeNJoccxH7XM/view) to generate Rosbag files: ```python3 sensordata_to_rosbag_fastlio.py bin_file_dir bag_name.bag```**!!!This ros1 bag should be convert to ros2!!!** To convert ros1 bag to ros2 bag, please follow the documentation [Convert rosbag versions](https://ternaris.gitlab.io/rosbags/topics/convert.html)
Run:
```
roslaunch fast_lio mapping_velodyne.launch
rosbag play YOUR_DOWNLOADED.bag
```
## 5.Implementation on UAV
In order to validate the robustness and computational efficiency of FAST-LIO in actual mobile robots, we build a small-scale quadrotor which can carry a Livox Avia LiDAR with 70 degree FoV and a DJI Manifold 2-C onboard computer with a 1.8 GHz Intel i7-8550U CPU and 8 G RAM, as shown in below.
The main structure of this UAV is 3d printed (Aluminum or PLA), the .stl file will be open-sourced in the future.
<div align="center">
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/uav01.jpg" width=40.5% >
<img src="https://raw.githubusercontent.com/hku-mars/FAST_LIO/main/doc/uav_system.png" width=57% >
</div>
## 6.Acknowledgments
Thanks for LOAM(J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time), [Livox_Mapping](https://github.com/Livox-SDK/livox_mapping), [LINS](https://github.com/ChaoqinRobotics/LINS---LiDAR-inertial-SLAM) and [Loam_Livox](https://github.com/hku-mars/loam_livox).
+46
View File
@@ -0,0 +1,46 @@
/**:
ros__parameters:
feature_extract_enable: false
point_filter_num: 3
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 1000.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
common:
lid_topic: "/livox/lidar"
imu_topic: "/livox/imu"
time_sync_en: false # ONLY turn on when external time synchronization is really not possible
time_offset_lidar_to_imu: 0.0 # Time offset between lidar and IMU calibrated by other algorithms, e.g. LI-Init (can be found in README).
# This param will take effect no matter what time_sync_en is. So if the time offset is not known exactly, please set as 0.0
preprocess:
lidar_type: 1 # 1 for Livox serials LiDAR, 2 for Velodyne LiDAR, 3 for ouster LiDAR,
scan_line: 6
blind: 4.0
mapping:
acc_cov: 0.1
gyr_cov: 0.1
b_acc_cov: 0.0001
b_gyr_cov: 0.0001
fov_degree: 90.0
det_range: 450.0
extrinsic_est_en: false # true: enable the online estimation of IMU-LiDAR extrinsic
extrinsic_T: [ 0.04165, 0.02326, -0.0284 ]
extrinsic_R: [ 1., 0., 0.,
0., 1., 0.,
0., 0., 1.]
publish:
path_en: false
scan_publish_en: true # false: close all the point cloud output
dense_publish_en: true # false: low down the points number in a global-frame point clouds scan.
scan_bodyframe_pub_en: true # true: output the point cloud scans in IMU-body-frame
pcd_save:
pcd_save_en: true
interval: -1 # how many LiDAR frames saved in each pcd file;
# -1 : all frames will be saved in ONE pcd file, may lead to memory crash when having too much frames.
+46
View File
@@ -0,0 +1,46 @@
/**:
ros__parameters:
feature_extract_enable: false
point_filter_num: 3
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 1000.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
common:
lid_topic: "/livox/lidar"
imu_topic: "/livox/imu"
time_sync_en: false # ONLY turn on when external time synchronization is really not possible
time_offset_lidar_to_imu: 0.0 # Time offset between lidar and IMU calibrated by other algorithms, e.g. LI-Init (can be found in README).
# This param will take effect no matter what time_sync_en is. So if the time offset is not known exactly, please set as 0.0
preprocess:
lidar_type: 1 # 1 for Livox serials LiDAR, 2 for Velodyne LiDAR, 3 for ouster LiDAR,
scan_line: 6
blind: 4.0
mapping:
acc_cov: 0.1
gyr_cov: 0.1
b_acc_cov: 0.0001
b_gyr_cov: 0.0001
fov_degree: 100.0
det_range: 260.0
extrinsic_est_en: true # true: enable the online estimation of IMU-LiDAR extrinsic
extrinsic_T: [ 0.05512, 0.02226, -0.0297 ]
extrinsic_R: [ 1., 0., 0.,
0., 1., 0.,
0., 0., 1.]
publish:
path_en: false
scan_publish_en: true # false: close all the point cloud output
dense_publish_en: true # false: low down the points number in a global-frame point clouds scan.
scan_bodyframe_pub_en: true # true: output the point cloud scans in IMU-body-frame
pcd_save:
pcd_save_en: true
interval: -1 # how many LiDAR frames saved in each pcd file;
# -1 : all frames will be saved in ONE pcd file, may lead to memory crash when having too much frames.
+50
View File
@@ -0,0 +1,50 @@
/**:
ros__parameters:
feature_extract_enable: false
point_filter_num: 3
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 400.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
common:
lid_topic: "/livox/lidar"
imu_topic: "/livox/imu"
time_sync_en: false # ONLY turn on when external time synchronization is really not possible
time_offset_lidar_to_imu: 0.0 # Time offset between lidar and IMU calibrated by other algorithms, e.g. LI-Init (can be found in README).
# This param will take effect no matter what time_sync_en is. So if the time offset is not known exactly, please set as 0.0
preprocess:
lidar_type: 1 # 1 for Livox serials LiDAR, 2 for Velodyne LiDAR, 3 for ouster LiDAR, 4 for any other pointcloud input
scan_line: 4
blind: 0.5
timestamp_unit: 3
scan_rate: 10
mapping:
acc_cov: 0.1
gyr_cov: 0.1
b_acc_cov: 0.0001
b_gyr_cov: 0.0001
fov_degree: 360.0
det_range: 60.0
extrinsic_est_en: true # true: enable the online estimation of IMU-LiDAR extrinsic
extrinsic_T: [ -0.011, -0.02329, 0.04412 ]
extrinsic_R: [ 1., 0., 0.,
0., 1., 0.,
0., 0., 1.]
publish:
path_en: true # true: publish Path
effect_map_en: true # true: publish Effects
map_en: true # true: publish Map cloud
scan_publish_en: true # false: close all the point cloud output
dense_publish_en: false # false: low down the points number in a global-frame point clouds scan.
scan_bodyframe_pub_en: true # true: output the point cloud scans in IMU-body-frame
pcd_save:
pcd_save_en: true
interval: -1 # how many LiDAR frames saved in each pcd file;
# -1 : all frames will be saved in ONE pcd file, may lead to memory crash when having too much frames.
+47
View File
@@ -0,0 +1,47 @@
/**:
ros__parameters:
feature_extract_enable: false
point_filter_num: 3
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 1000.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
common:
lid_topic: "/os_cloud_node/points"
imu_topic: "/os_cloud_node/imu"
time_sync_en: false # ONLY turn on when external time synchronization is really not possible
time_offset_lidar_to_imu: 0.0 # Time offset between lidar and IMU calibrated by other algorithms, e.g. LI-Init (can be found in README).
# This param will take effect no matter what time_sync_en is. So if the time offset is not known exactly, please set as 0.0
preprocess:
lidar_type: 3 # 1 for Livox serials LiDAR, 2 for Velodyne LiDAR, 3 for ouster LiDAR,
scan_line: 64
timestamp_unit: 3 # 0-second, 1-milisecond, 2-microsecond, 3-nanosecond.
blind: 4.0
mapping:
acc_cov: 0.1
gyr_cov: 0.1
b_acc_cov: 0.0001
b_gyr_cov: 0.0001
fov_degree: 360.0
det_range: 150.0
extrinsic_est_en: false # true: enable the online estimation of IMU-LiDAR extrinsic
extrinsic_T: [ 0.0, 0.0, 0.0 ]
extrinsic_R: [1., 0., 0.,
0., 1., 0.,
0., 0., 1.]
publish:
path_en: false
scan_publish_en: true # false: close all the point cloud output
dense_publish_en: true # false: low down the points number in a global-frame point clouds scan.
scan_bodyframe_pub_en: true # true: output the point cloud scans in IMU-body-frame
pcd_save:
pcd_save_en: true
interval: -1 # how many LiDAR frames saved in each pcd file;
# -1 : all frames will be saved in ONE pcd file, may lead to memory crash when having too much frames.
+61
View File
@@ -0,0 +1,61 @@
/**:
ros__parameters:
# ================== Global Settings ==================
feature_extract_enable: false
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 1000.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
# ================== Sensor Topics ==================
common:
lid_topic: "/unilidar/cloud" # LiDAR点云话题
imu_topic: "/unilidar/imu" # IMU话题
time_sync_en: false # 关闭内部时间同步(若需要同步请设为true)
time_offset_lidar_to_imu: 0.0 # IMU到LiDAR时间偏移(与您配置的time_lag_imu_to_lidar取反)
# ================== LiDAR预处理 ==================
preprocess:
lidar_type: 5 # 雷达类型(需确认类型编号对应关系)
scan_line: 18 # 扫描线数
point_filter_num: 1 # 点云降采样率(原con_frame_num
blind: 0.5 # 盲区过滤半径(米)
timestamp_unit: 0 # 时间戳单位:0=秒,1=毫秒,2=微秒,3=纳秒
# ================== SLAM核心参数 ==================
mapping:
# IMU参数
imu_en: true # 启用IMU
imu_time_inte: 0.004 # IMU采样间隔(1/frequency
acc_cov: 0.1 # 加速度计噪声协方差
gyr_cov: 0.1 # 陀螺仪噪声协方差
b_acc_cov: 0.0001 # 加速度计零偏噪声
b_gyr_cov: 0.0001 # 陀螺仪零偏噪声
# 外参标定
extrinsic_est_en: false # 关闭在线外参标定
extrinsic_T: [0.007698, 0.014655, -0.00667] # IMU到LiDAR平移
extrinsic_R: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] # IMU到LiDAR旋转矩阵
# 环境参数
fov_degree: 180.0 # 有效FOV角度
det_range: 100.0 # 最大探测距离(米)
plane_thr: 0.1 # 平面拟合阈值
# 重力对齐
gravity_align: true # 启用重力对齐
gravity: [0.0, 0.0, -9.810] # 重力向量(与您配置一致)
# ================== 输出设置 ==================
publish:
path_en: true # 发布轨迹路径
scan_publish_en: true # 发布原始点云
scan_bodyframe_pub_en: true # 发布IMU坐标系点云
dense_publish_en: true # 发布稠密地图
# ================== 地图保存 ==================
pcd_save:
pcd_save_en: true # 启用PCD保存
interval: -1 # 全帧保存(注意内存风险)
+48
View File
@@ -0,0 +1,48 @@
/**:
ros__parameters:
feature_extract_enable: false
point_filter_num: 4
max_iteration: 3
filter_size_surf: 0.5
filter_size_map: 0.5
cube_side_length: 1000.0
runtime_pos_log_enable: false
map_file_path: "./test.pcd"
common:
lid_topic: "/velodyne_points"
imu_topic: "/imu/data"
time_sync_en: false # ONLY turn on when external time synchronization is really not possible
time_offset_lidar_to_imu: 0.0 # Time offset between lidar and IMU calibrated by other algorithms, e.g. LI-Init (can be found in README).
# This param will take effect no matter what time_sync_en is. So if the time offset is not known exactly, please set as 0.0
preprocess:
lidar_type: 2 # 1 for Livox serials LiDAR, 2 for Velodyne LiDAR, 3 for ouster LiDAR,
scan_line: 32
scan_rate: 10 # only need to be set for velodyne, unit: Hz,
timestamp_unit: 2 # the unit of time/t field in the PointCloud2 rostopic: 0-second, 1-milisecond, 2-microsecond, 3-nanosecond.
blind: 2.0
mapping:
acc_cov: 0.1
gyr_cov: 0.1
b_acc_cov: 0.0001
b_gyr_cov: 0.0001
fov_degree: 360.0
det_range: 100.0
extrinsic_est_en: false # true: enable the online estimation of IMU-LiDAR extrinsic,
extrinsic_T: [ 0., 0., 0.28]
extrinsic_R: [ 1., 0., 0.,
0., 1., 0.,
0., 0., 1.]
publish:
path_en: false
scan_publish_en: true # false: close all the point cloud output
dense_publish_en: true # false: low down the points number in a global-frame point clouds scan.
scan_bodyframe_pub_en: true # true: output the point cloud scans in IMU-body-frame
pcd_save:
pcd_save_en: true
interval: -1 # how many LiDAR frames saved in each pcd file;
# -1 : all frames will be saved in ONE pcd file, may lead to memory crash when having too much frames.
+103
View File
@@ -0,0 +1,103 @@
#ifndef EXP_MAT_H
#define EXP_MAT_H
#include <math.h>
#include <Eigen/Core>
#include <opencv2/core.hpp>
// #include <common_lib.h>
#define SKEW_SYM_MATRX(v) 0.0,-v[2],v[1],v[2],0.0,-v[0],-v[1],v[0],0.0
template<typename T>
Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &&ang)
{
T ang_norm = ang.norm();
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (ang_norm > 0.0000001)
{
Eigen::Matrix<T, 3, 1> r_axis = ang / ang_norm;
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_axis);
/// Roderigous Tranformation
return Eye3 + std::sin(ang_norm) * K + (1.0 - std::cos(ang_norm)) * K * K;
}
else
{
return Eye3;
}
}
template<typename T, typename Ts>
Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &ang_vel, const Ts &dt)
{
T ang_vel_norm = ang_vel.norm();
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (ang_vel_norm > 0.0000001)
{
Eigen::Matrix<T, 3, 1> r_axis = ang_vel / ang_vel_norm;
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_axis);
T r_ang = ang_vel_norm * dt;
/// Roderigous Tranformation
return Eye3 + std::sin(r_ang) * K + (1.0 - std::cos(r_ang)) * K * K;
}
else
{
return Eye3;
}
}
template<typename T>
Eigen::Matrix<T, 3, 3> Exp(const T &v1, const T &v2, const T &v3)
{
T &&norm = sqrt(v1 * v1 + v2 * v2 + v3 * v3);
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (norm > 0.00001)
{
T r_ang[3] = {v1 / norm, v2 / norm, v3 / norm};
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_ang);
/// Roderigous Tranformation
return Eye3 + std::sin(norm) * K + (1.0 - std::cos(norm)) * K * K;
}
else
{
return Eye3;
}
}
/* Logrithm of a Rotation Matrix */
template<typename T>
Eigen::Matrix<T,3,1> Log(const Eigen::Matrix<T, 3, 3> &R)
{
T &&theta = std::acos(0.5 * (R.trace() - 1));
Eigen::Matrix<T,3,1> K(R(2,1) - R(1,2), R(0,2) - R(2,0), R(1,0) - R(0,1));
return (std::abs(theta) < 0.001) ? (0.5 * K) : (0.5 * theta / std::sin(theta) * K);
}
// template<typename T>
// cv::Mat Exp(const T &v1, const T &v2, const T &v3)
// {
// T norm = sqrt(v1 * v1 + v2 * v2 + v3 * v3);
// cv::Mat Eye3 = cv::Mat::eye(3, 3, CV_32F);
// if (norm > 0.0000001)
// {
// T r_ang[3] = {v1 / norm, v2 / norm, v3 / norm};
// cv::Mat K = (cv::Mat_<T>(3,3) << SKEW_SYM_MATRX(r_ang));
// /// Roderigous Tranformation
// return Eye3 + std::sin(norm) * K + (1.0 - std::cos(norm)) * K * K;
// }
// else
// {
// return Eye3;
// }
// }
#endif
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Author: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
#ifndef __MEKFOM_UTIL_HPP__
#define __MEKFOM_UTIL_HPP__
#include <Eigen/Core>
#include "../mtk/src/mtkmath.hpp"
namespace esekfom {
template <typename T1, typename T2>
class is_same {
public:
operator bool() {
return false;
}
};
template<typename T1>
class is_same<T1, T1> {
public:
operator bool() {
return true;
}
};
template <typename T>
class is_double {
public:
operator bool() {
return false;
}
};
template<>
class is_double<double> {
public:
operator bool() {
return true;
}
};
template<typename T>
static T
id(const T &x)
{
return x;
}
} // namespace esekfom
#endif // __MEKFOM_UTIL_HPP__
+229
View File
@@ -0,0 +1,229 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/build_manifold.hpp
* @brief Macro to automatically construct compound manifolds.
*
*/
#ifndef MTK_AUTOCONSTRUCT_HPP_
#define MTK_AUTOCONSTRUCT_HPP_
#include <vector>
#include <boost/preprocessor/seq.hpp>
#include <boost/preprocessor/cat.hpp>
#include <Eigen/Core>
#include "src/SubManifold.hpp"
#include "startIdx.hpp"
#ifndef PARSED_BY_DOXYGEN
//////// internals //////
#define MTK_APPLY_MACRO_ON_TUPLE(r, macro, tuple) macro tuple
#define MTK_TRANSFORM_COMMA(macro, entries) BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM_S(1, MTK_APPLY_MACRO_ON_TUPLE, macro, entries))
#define MTK_TRANSFORM(macro, entries) BOOST_PP_SEQ_FOR_EACH_R(1, MTK_APPLY_MACRO_ON_TUPLE, macro, entries)
#define MTK_CONSTRUCTOR_ARG( type, id) const type& id = type()
#define MTK_CONSTRUCTOR_COPY( type, id) id(id)
#define MTK_BOXPLUS( type, id) id.boxplus(MTK::subvector(__vec, &self::id), __scale);
#define MTK_OPLUS( type, id) id.oplus(MTK::subvector_(__vec, &self::id), __scale);
#define MTK_BOXMINUS( type, id) id.boxminus(MTK::subvector(__res, &self::id), __oth.id);
#define MTK_S2_hat( type, id) if(id.IDX == idx){id.S2_hat(res);}
#define MTK_S2_Nx_yy( type, id) if(id.IDX == idx){id.S2_Nx_yy(res);}
#define MTK_S2_Mx( type, id) if(id.IDX == idx){id.S2_Mx(res, dx);}
#define MTK_OSTREAM( type, id) << __var.id << " "
#define MTK_ISTREAM( type, id) >> __var.id
#define MTK_S2_state( type, id) if(id.TYP == 1){S2_state.push_back(std::make_pair(id.IDX, id.DIM));}
#define MTK_SO3_state( type, id) if(id.TYP == 2){(SO3_state).push_back(std::make_pair(id.IDX, id.DIM));}
#define MTK_vect_state( type, id) if(id.TYP == 0){(vect_state).push_back(std::make_pair(std::make_pair(id.IDX, id.DIM), type::DOF));}
#define MTK_SUBVARLIST(seq, S2state, SO3state) \
BOOST_PP_FOR_1( \
( \
BOOST_PP_SEQ_SIZE(seq), \
BOOST_PP_SEQ_HEAD(seq), \
BOOST_PP_SEQ_TAIL(seq) (~), \
0,\
0,\
S2state,\
SO3state ),\
MTK_ENTRIES_TEST, MTK_ENTRIES_NEXT, MTK_ENTRIES_OUTPUT)
#define MTK_PUT_TYPE(type, id, dof, dim, S2state, SO3state) \
MTK::SubManifold<type, dof, dim> id;
#define MTK_PUT_TYPE_AND_ENUM(type, id, dof, dim, S2state, SO3state) \
MTK_PUT_TYPE(type, id, dof, dim, S2state, SO3state) \
enum {DOF = type::DOF + dof}; \
enum {DIM = type::DIM+dim}; \
typedef type::scalar scalar;
#define MTK_ENTRIES_OUTPUT(r, state) MTK_ENTRIES_OUTPUT_I state
#define MTK_ENTRIES_OUTPUT_I(s, head, seq, dof, dim, S2state, SO3state) \
MTK_APPLY_MACRO_ON_TUPLE(~, \
BOOST_PP_IF(BOOST_PP_DEC(s), MTK_PUT_TYPE, MTK_PUT_TYPE_AND_ENUM), \
( BOOST_PP_TUPLE_REM_2 head, dof, dim, S2state, SO3state))
#define MTK_ENTRIES_TEST(r, state) MTK_TUPLE_ELEM_4_0 state
//! this used to be BOOST_PP_TUPLE_ELEM_4_0:
#define MTK_TUPLE_ELEM_4_0(a,b,c,d,e,f, g) a
#define MTK_ENTRIES_NEXT(r, state) MTK_ENTRIES_NEXT_I state
#define MTK_ENTRIES_NEXT_I(len, head, seq, dof, dim, S2state, SO3state) ( \
BOOST_PP_DEC(len), \
BOOST_PP_SEQ_HEAD(seq), \
BOOST_PP_SEQ_TAIL(seq), \
dof + BOOST_PP_TUPLE_ELEM_2_0 head::DOF,\
dim + BOOST_PP_TUPLE_ELEM_2_0 head::DIM,\
S2state,\
SO3state)
#endif /* not PARSED_BY_DOXYGEN */
/**
* Construct a manifold.
* @param name is the class-name of the manifold,
* @param entries is the list of sub manifolds
*
* Entries must be given in a list like this:
* @code
* typedef MTK::trafo<MTK::SO3<double> > Pose;
* typedef MTK::vect<double, 3> Vec3;
* MTK_BUILD_MANIFOLD(imu_state,
* ((Pose, pose))
* ((Vec3, vel))
* ((Vec3, acc_bias))
* )
* @endcode
* Whitespace is optional, but the double parentheses are necessary.
* Construction is done entirely in preprocessor.
* After construction @a name is also a manifold. Its members can be
* accessed by names given in @a entries.
*
* @note Variable types are not allowed to have commas, thus types like
* @c vect<double, 3> need to be typedef'ed ahead.
*/
#define MTK_BUILD_MANIFOLD(name, entries) \
struct name { \
typedef name self; \
std::vector<std::pair<int, int> > S2_state;\
std::vector<std::pair<int, int> > SO3_state;\
std::vector<std::pair<std::pair<int, int>, int> > vect_state;\
MTK_SUBVARLIST(entries, S2_state, SO3_state) \
name ( \
MTK_TRANSFORM_COMMA(MTK_CONSTRUCTOR_ARG, entries) \
) : \
MTK_TRANSFORM_COMMA(MTK_CONSTRUCTOR_COPY, entries) {}\
int getDOF() const { return DOF; } \
void boxplus(const MTK::vectview<const scalar, DOF> & __vec, scalar __scale = 1 ) { \
MTK_TRANSFORM(MTK_BOXPLUS, entries)\
} \
void oplus(const MTK::vectview<const scalar, DIM> & __vec, scalar __scale = 1 ) { \
MTK_TRANSFORM(MTK_OPLUS, entries)\
} \
void boxminus(MTK::vectview<scalar,DOF> __res, const name& __oth) const { \
MTK_TRANSFORM(MTK_BOXMINUS, entries)\
} \
friend std::ostream& operator<<(std::ostream& __os, const name& __var){ \
return __os MTK_TRANSFORM(MTK_OSTREAM, entries); \
} \
void build_S2_state(){\
MTK_TRANSFORM(MTK_S2_state, entries)\
}\
void build_vect_state(){\
MTK_TRANSFORM(MTK_vect_state, entries)\
}\
void build_SO3_state(){\
MTK_TRANSFORM(MTK_SO3_state, entries)\
}\
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res, int idx) {\
MTK_TRANSFORM(MTK_S2_hat, entries)\
}\
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res, int idx) {\
MTK_TRANSFORM(MTK_S2_Nx_yy, entries)\
}\
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, Eigen::Matrix<scalar, 2, 1> dx, int idx) {\
MTK_TRANSFORM(MTK_S2_Mx, entries)\
}\
friend std::istream& operator>>(std::istream& __is, name& __var){ \
return __is MTK_TRANSFORM(MTK_ISTREAM, entries); \
} \
};
#endif /*MTK_AUTOCONSTRUCT_HPP_*/
+123
View File
@@ -0,0 +1,123 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/src/SubManifold.hpp
* @brief Defines the SubManifold class
*/
#ifndef SUBMANIFOLD_HPP_
#define SUBMANIFOLD_HPP_
#include "vectview.hpp"
namespace MTK {
/**
* @ingroup SubManifolds
* Helper class for compound manifolds.
* This class wraps a manifold T and provides an enum IDX refering to the
* index of the SubManifold within the compound manifold.
*
* Memberpointers to a submanifold can be used for @ref SubManifolds "functions accessing submanifolds".
*
* @tparam T The manifold type of the sub-type
* @tparam idx The index of the sub-type within the compound manifold
*/
template<class T, int idx, int dim>
struct SubManifold : public T
{
enum {IDX = idx, DIM = dim /*!< index of the sub-type within the compound manifold */ };
//! manifold type
typedef T type;
//! Construct from derived type
template<class X>
explicit
SubManifold(const X& t) : T(t) {};
//! Construct from internal type
//explicit
SubManifold(const T& t) : T(t) {};
//! inherit assignment operator
using T::operator=;
};
} // namespace MTK
#endif /* SUBMANIFOLD_HPP_ */
+294
View File
@@ -0,0 +1,294 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/src/mtkmath.hpp
* @brief several math utility functions.
*/
#ifndef MTKMATH_H_
#define MTKMATH_H_
#include <cmath>
#include <boost/math/tools/precision.hpp>
#include "../types/vect.hpp"
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
namespace MTK {
namespace internal {
template<class Manifold>
struct traits {
typedef typename Manifold::scalar scalar;
enum {DOF = Manifold::DOF};
typedef vect<DOF, scalar> vectorized_type;
typedef Eigen::Matrix<scalar, DOF, DOF> matrix_type;
};
template<>
struct traits<float> : traits<Scalar<float> > {};
template<>
struct traits<double> : traits<Scalar<double> > {};
} // namespace internal
/**
* \defgroup MTKMath Mathematical helper functions
*/
//@{
//! constant @f$ \pi @f$
const double pi = M_PI;
template<class scalar> inline scalar tolerance();
template<> inline float tolerance<float >() { return 1e-5f; }
template<> inline double tolerance<double>() { return 1e-11; }
/**
* normalize @a x to @f$[-bound, bound] @f$.
*
* result for @f$ x = bound + 2\cdot n\cdot bound @f$ is arbitrary @f$\pm bound @f$.
*/
template<class scalar>
inline scalar normalize(scalar x, scalar bound){ //not used
if(std::fabs(x) <= bound) return x;
int r = (int)(x *(scalar(1.0)/ bound));
return x - ((r + (r>>31) + 1) & ~1)*bound;
}
/**
* Calculate cosine and sinc of sqrt(x2).
* @param x2 the squared angle must be non-negative
* @return a pair containing cos and sinc of sqrt(x2)
*/
template<class scalar>
std::pair<scalar, scalar> cos_sinc_sqrt(const scalar &x2){
using std::sqrt;
using std::cos;
using std::sin;
static scalar const taylor_0_bound = boost::math::tools::epsilon<scalar>();
static scalar const taylor_2_bound = sqrt(taylor_0_bound);
static scalar const taylor_n_bound = sqrt(taylor_2_bound);
assert(x2>=0 && "argument must be non-negative");
// FIXME check if bigger bounds are possible
if(x2>=taylor_n_bound) {
// slow fall-back solution
scalar x = sqrt(x2);
return std::make_pair(cos(x), sin(x)/x); // x is greater than 0.
}
// FIXME Replace by Horner-Scheme (4 instead of 5 FLOP/term, numerically more stable, theoretically cos and sinc can be calculated in parallel using SSE2 mulpd/addpd)
// TODO Find optimal coefficients using Remez algorithm
static scalar const inv[] = {1/3., 1/4., 1/5., 1/6., 1/7., 1/8., 1/9.};
scalar cosi = 1., sinc=1;
scalar term = -1/2. * x2;
for(int i=0; i<3; ++i) {
cosi += term;
term *= inv[2*i];
sinc += term;
term *= -inv[2*i+1] * x2;
}
return std::make_pair(cosi, sinc);
}
template<typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> hat(const Base& v) {
Eigen::Matrix<typename Base::scalar, 3, 3> res;
res << 0, -v[2], v[1],
v[2], 0, -v[0],
-v[1], v[0], 0;
return res;
}
template<typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_inv_trans(const Base& v){
Eigen::Matrix<typename Base::scalar, 3, 3> res;
if(v.norm() > MTK::tolerance<typename Base::scalar>())
{
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + 0.5 * hat<Base>(v) + (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();
}
else
{
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
}
return res;
}
template<typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_inv(const Base& v){
Eigen::Matrix<typename Base::scalar, 3, 3> res;
if(v.norm() > MTK::tolerance<typename Base::scalar>())
{
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() - 0.5 * hat<Base>(v) + (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();
}
else
{
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
}
return res;
}
template<typename scalar>
Eigen::Matrix<scalar, 2, 3> S2_w_expw_( Eigen::Matrix<scalar, 2, 1> v, scalar length)
{
Eigen::Matrix<scalar, 2, 3> res;
scalar norm = std::sqrt(v[0]*v[0] + v[1]*v[1]);
if(norm < MTK::tolerance<scalar>()){
res = Eigen::Matrix<scalar, 2, 3>::Zero();
res(0, 1) = 1;
res(1, 2) = 1;
res /= length;
}
else{
res << -v[0]*(1/norm-1/std::tan(norm))/std::sin(norm), norm/std::sin(norm), 0,
-v[1]*(1/norm-1/std::tan(norm))/std::sin(norm), 0, norm/std::sin(norm);
res /= length;
}
}
template<typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_matrix(const Base & v){
Eigen::Matrix<typename Base::scalar, 3, 3> res;
double squaredNorm = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
double norm = std::sqrt(squaredNorm);
if(norm < MTK::tolerance<typename Base::scalar>()){
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
}
else{
res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + (1 - std::cos(norm)) / squaredNorm * hat(v) + (1 - std::sin(norm) / norm) / squaredNorm * hat(v) * hat(v);
}
return res;
}
template<class scalar, int n>
scalar exp(vectview<scalar, n> result, vectview<const scalar, n> vec, const scalar& scale = 1) {
scalar norm2 = vec.squaredNorm();
std::pair<scalar, scalar> cos_sinc = cos_sinc_sqrt(scale*scale * norm2);
scalar mult = cos_sinc.second * scale;
result = mult * vec;
return cos_sinc.first;
}
/**
* Inverse function to @c exp.
*
* @param result @c vectview to the result
* @param w scalar part of input
* @param vec vector part of input
* @param scale scale result by this value
* @param plus_minus_periodicity if true values @f$[w, vec]@f$ and @f$[-w, -vec]@f$ give the same result
*/
template<class scalar, int n>
void log(vectview<scalar, n> result,
const scalar &w, const vectview<const scalar, n> vec,
const scalar &scale, bool plus_minus_periodicity)
{
// FIXME implement optimized case for vec.squaredNorm() <= tolerance() * (w*w) via Rational Remez approximation ~> only one division
scalar nv = vec.norm();
if(nv < tolerance<scalar>()) {
if(!plus_minus_periodicity && w < 0) {
// find the maximal entry:
int i;
nv = vec.cwiseAbs().maxCoeff(&i);
result = scale * std::atan2(nv, w) * vect<n, scalar>::Unit(i);
return;
}
nv = tolerance<scalar>();
}
scalar s = scale / nv * (plus_minus_periodicity ? std::atan(nv / w) : std::atan2(nv, w) );
result = s * vec;
}
} // namespace MTK
#endif /* MTKMATH_H_ */
+168
View File
@@ -0,0 +1,168 @@
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/src/vectview.hpp
* @brief Wrapper class around a pointer used as interface for plain vectors.
*/
#ifndef VECTVIEW_HPP_
#define VECTVIEW_HPP_
#include <Eigen/Core>
namespace MTK {
/**
* A view to a vector.
* Essentially, @c vectview is only a pointer to @c scalar but can be used directly in @c Eigen expressions.
* The dimension of the vector is given as template parameter and type-checked when used in expressions.
* Data has to be modifiable.
*
* @tparam scalar Scalar type of the vector.
* @tparam dim Dimension of the vector.
*
* @todo @c vectview can be replaced by simple inheritance of @c Eigen::Map, as soon as they get const-correct
*/
namespace internal {
template<class Base, class T1, class T2>
struct CovBlock {
typedef typename Eigen::Block<Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF>, T1::DOF, T2::DOF> Type;
typedef typename Eigen::Block<const Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF>, T1::DOF, T2::DOF> ConstType;
};
template<class Base, class T1, class T2>
struct CovBlock_ {
typedef typename Eigen::Block<Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM>, T1::DIM, T2::DIM> Type;
typedef typename Eigen::Block<const Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM>, T1::DIM, T2::DIM> ConstType;
};
template<typename Base1, typename Base2, typename T1, typename T2>
struct CrossCovBlock {
typedef typename Eigen::Block<Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF>, T1::DOF, T2::DOF> Type;
typedef typename Eigen::Block<const Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF>, T1::DOF, T2::DOF> ConstType;
};
template<typename Base1, typename Base2, typename T1, typename T2>
struct CrossCovBlock_ {
typedef typename Eigen::Block<Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM>, T1::DIM, T2::DIM> Type;
typedef typename Eigen::Block<const Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM>, T1::DIM, T2::DIM> ConstType;
};
template<class scalar, int dim>
struct VectviewBase {
typedef Eigen::Matrix<scalar, dim, 1> matrix_type;
typedef typename matrix_type::MapType Type;
typedef typename matrix_type::ConstMapType ConstType;
};
template<class T>
struct UnalignedType {
typedef T type;
};
}
template<class scalar, int dim>
class vectview : public internal::VectviewBase<scalar, dim>::Type {
typedef internal::VectviewBase<scalar, dim> VectviewBase;
public:
//! plain matrix type
typedef typename VectviewBase::matrix_type matrix_type;
//! base type
typedef typename VectviewBase::Type base;
//! construct from pointer
explicit
vectview(scalar* data, int dim_=dim) : base(data, dim_) {}
//! construct from plain matrix
vectview(matrix_type& m) : base(m.data(), m.size()) {}
//! construct from another @c vectview
vectview(const vectview &v) : base(v) {}
//! construct from Eigen::Block:
template<class Base>
vectview(Eigen::VectorBlock<Base, dim> block) : base(&block.coeffRef(0), block.size()) {}
template<class Base, bool PacketAccess>
vectview(Eigen::Block<Base, dim, 1, PacketAccess> block) : base(&block.coeffRef(0), block.size()) {}
//! inherit assignment operator
using base::operator=;
//! data pointer
scalar* data() {return const_cast<scalar*>(base::data());}
};
/**
* @c const version of @c vectview.
* Compared to @c Eigen::Map this implementation is const correct, i.e.,
* data will not be modifiable using this view.
*
* @tparam scalar Scalar type of the vector.
* @tparam dim Dimension of the vector.
*
* @sa vectview
*/
template<class scalar, int dim>
class vectview<const scalar, dim> : public internal::VectviewBase<scalar, dim>::ConstType {
typedef internal::VectviewBase<scalar, dim> VectviewBase;
public:
//! plain matrix type
typedef typename VectviewBase::matrix_type matrix_type;
//! base type
typedef typename VectviewBase::ConstType base;
//! construct from const pointer
explicit
vectview(const scalar* data, int dim_ = dim) : base(data, dim_) {}
//! construct from column vector
template<int options>
vectview(const Eigen::Matrix<scalar, dim, 1, options>& m) : base(m.data()) {}
//! construct from row vector
template<int options, int phony>
vectview(const Eigen::Matrix<scalar, 1, dim, options, phony>& m) : base(m.data()) {}
//! construct from another @c vectview
vectview(vectview<scalar, dim> x) : base(x.data()) {}
//! construct from base
vectview(const base &x) : base(x) {}
/**
* Construct from Block
* @todo adapt this, when Block gets const-correct
*/
template<class Base>
vectview(Eigen::VectorBlock<Base, dim> block) : base(&block.coeffRef(0)) {}
template<class Base, bool PacketAccess>
vectview(Eigen::Block<Base, dim, 1, PacketAccess> block) : base(&block.coeffRef(0)) {}
};
} // namespace MTK
#endif /* VECTVIEW_HPP_ */
+328
View File
@@ -0,0 +1,328 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/startIdx.hpp
* @brief Tools to access sub-elements of compound manifolds.
*/
#ifndef GET_START_INDEX_H_
#define GET_START_INDEX_H_
#include <Eigen/Core>
#include "src/SubManifold.hpp"
#include "src/vectview.hpp"
namespace MTK {
/**
* \defgroup SubManifolds Accessing Submanifolds
* For compound manifolds constructed using MTK_BUILD_MANIFOLD, member pointers
* can be used to get sub-vectors or matrix-blocks of a corresponding big matrix.
* E.g. for a type @a pose consisting of @a orient and @a trans the member pointers
* @c &pose::orient and @c &pose::trans give all required information and are still
* valid if the base type gets extended or the actual types of @a orient and @a trans
* change (e.g. from 2D to 3D).
*
* @todo Maybe require manifolds to typedef MatrixType and VectorType, etc.
*/
//@{
/**
* Determine the index of a sub-variable within a compound variable.
*/
template<class Base, class T, int idx, int dim>
int getStartIdx( MTK::SubManifold<T, idx, dim> Base::*)
{
return idx;
}
template<class Base, class T, int idx, int dim>
int getStartIdx_( MTK::SubManifold<T, idx, dim> Base::*)
{
return dim;
}
/**
* Determine the degrees of freedom of a sub-variable within a compound variable.
*/
template<class Base, class T, int idx, int dim>
int getDof( MTK::SubManifold<T, idx, dim> Base::*)
{
return T::DOF;
}
template<class Base, class T, int idx, int dim>
int getDim( MTK::SubManifold<T, idx, dim> Base::*)
{
return T::DIM;
}
/**
* set the diagonal elements of a covariance matrix corresponding to a sub-variable
*/
template<class Base, class T, int idx, int dim>
void setDiagonal(Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> &cov,
MTK::SubManifold<T, idx, dim> Base::*, const typename Base::scalar &val)
{
cov.diagonal().template segment<T::DOF>(idx).setConstant(val);
}
template<class Base, class T, int idx, int dim>
void setDiagonal_(Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> &cov,
MTK::SubManifold<T, idx, dim> Base::*, const typename Base::scalar &val)
{
cov.diagonal().template segment<T::DIM>(dim).setConstant(val);
}
/**
* Get the subblock of corresponding to two members, i.e.
* \code
* Eigen::Matrix<double, Pose::DOF, Pose::DOF> m;
* MTK::subblock(m, &Pose::orient, &Pose::trans) = some_expression;
* MTK::subblock(m, &Pose::trans, &Pose::orient) = some_expression.trans();
* \endcode
* lets you modify mixed covariance entries in a bigger covariance matrix.
*/
template<class Base, class T1, int idx1, int dim1, class T2, int idx2, int dim2>
typename MTK::internal::CovBlock<Base, T1, T2>::Type
subblock(Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> &cov,
MTK::SubManifold<T1, idx1, dim1> Base::*, MTK::SubManifold<T2, idx2, dim2> Base::*)
{
return cov.template block<T1::DOF, T2::DOF>(idx1, idx2);
}
template<class Base, class T1, int idx1, int dim1, class T2, int idx2, int dim2>
typename MTK::internal::CovBlock_<Base, T1, T2>::Type
subblock_(Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> &cov,
MTK::SubManifold<T1, idx1, dim1> Base::*, MTK::SubManifold<T2, idx2, dim2> Base::*)
{
return cov.template block<T1::DIM, T2::DIM>(dim1, dim2);
}
template<typename Base1, typename Base2, typename T1, typename T2, int idx1, int idx2, int dim1, int dim2>
typename MTK::internal::CrossCovBlock<Base1, Base2, T1, T2>::Type
subblock(Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF> &cov, MTK::SubManifold<T1, idx1, dim1> Base1::*, MTK::SubManifold<T2, idx2, dim2> Base2::*)
{
return cov.template block<T1::DOF, T2::DOF>(idx1, idx2);
}
template<typename Base1, typename Base2, typename T1, typename T2, int idx1, int idx2, int dim1, int dim2>
typename MTK::internal::CrossCovBlock_<Base1, Base2, T1, T2>::Type
subblock_(Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM> &cov, MTK::SubManifold<T1, idx1, dim1> Base1::*, MTK::SubManifold<T2, idx2, dim2> Base2::*)
{
return cov.template block<T1::DIM, T2::DIM>(dim1, dim2);
}
/**
* Get the subblock of corresponding to a member, i.e.
* \code
* Eigen::Matrix<double, Pose::DOF, Pose::DOF> m;
* MTK::subblock(m, &Pose::orient) = some_expression;
* \endcode
* lets you modify covariance entries in a bigger covariance matrix.
*/
template<class Base, class T, int idx, int dim>
typename MTK::internal::CovBlock_<Base, T, T>::Type
subblock_(Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> &cov,
MTK::SubManifold<T, idx, dim> Base::*)
{
return cov.template block<T::DIM, T::DIM>(dim, dim);
}
template<class Base, class T, int idx, int dim>
typename MTK::internal::CovBlock<Base, T, T>::Type
subblock(Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> &cov,
MTK::SubManifold<T, idx, dim> Base::*)
{
return cov.template block<T::DOF, T::DOF>(idx, idx);
}
template<typename Base>
class get_cov {
public:
typedef Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> type;
typedef const Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> const_type;
};
template<typename Base>
class get_cov_ {
public:
typedef Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> type;
typedef const Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> const_type;
};
template<typename Base1, typename Base2>
class get_cross_cov {
public:
typedef Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF> type;
typedef const type const_type;
};
template<typename Base1, typename Base2>
class get_cross_cov_ {
public:
typedef Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM> type;
typedef const type const_type;
};
template<class Base, class T, int idx, int dim>
vectview<typename Base::scalar, T::DIM>
subvector_impl_(vectview<typename Base::scalar, Base::DIM> vec, SubManifold<T, idx, dim> Base::*)
{
return vec.template segment<T::DIM>(dim);
}
template<class Base, class T, int idx, int dim>
vectview<typename Base::scalar, T::DOF>
subvector_impl(vectview<typename Base::scalar, Base::DOF> vec, SubManifold<T, idx, dim> Base::*)
{
return vec.template segment<T::DOF>(idx);
}
/**
* Get the subvector corresponding to a sub-manifold from a bigger vector.
*/
template<class Scalar, int BaseDIM, class Base, class T, int idx, int dim>
vectview<Scalar, T::DIM>
subvector_(vectview<Scalar, BaseDIM> vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl_(vec, ptr);
}
template<class Scalar, int BaseDOF, class Base, class T, int idx, int dim>
vectview<Scalar, T::DOF>
subvector(vectview<Scalar, BaseDOF> vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl(vec, ptr);
}
/**
* @todo This should be covered already by subvector(vectview<typename Base::scalar,Base::DOF> vec,SubManifold<T,idx> Base::*)
*/
template<class Scalar, int BaseDOF, class Base, class T, int idx, int dim>
vectview<Scalar, T::DOF>
subvector(Eigen::Matrix<Scalar, BaseDOF, 1>& vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl(vectview<Scalar, BaseDOF>(vec), ptr);
}
template<class Scalar, int BaseDIM, class Base, class T, int idx, int dim>
vectview<Scalar, T::DIM>
subvector_(Eigen::Matrix<Scalar, BaseDIM, 1>& vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl_(vectview<Scalar, BaseDIM>(vec), ptr);
}
template<class Scalar, int BaseDIM, class Base, class T, int idx, int dim>
vectview<const Scalar, T::DIM>
subvector_(const Eigen::Matrix<Scalar, BaseDIM, 1>& vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl_(vectview<const Scalar, BaseDIM>(vec), ptr);
}
template<class Scalar, int BaseDOF, class Base, class T, int idx, int dim>
vectview<const Scalar, T::DOF>
subvector(const Eigen::Matrix<Scalar, BaseDOF, 1>& vec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl(vectview<const Scalar, BaseDOF>(vec), ptr);
}
/**
* const version of subvector(vectview<typename Base::scalar,Base::DOF> vec,SubManifold<T,idx> Base::*)
*/
template<class Base, class T, int idx, int dim>
vectview<const typename Base::scalar, T::DOF>
subvector_impl(const vectview<const typename Base::scalar, Base::DOF> cvec, SubManifold<T, idx, dim> Base::*)
{
return cvec.template segment<T::DOF>(idx);
}
template<class Base, class T, int idx, int dim>
vectview<const typename Base::scalar, T::DIM>
subvector_impl_(const vectview<const typename Base::scalar, Base::DIM> cvec, SubManifold<T, idx, dim> Base::*)
{
return cvec.template segment<T::DIM>(dim);
}
template<class Scalar, int BaseDOF, class Base, class T, int idx, int dim>
vectview<const Scalar, T::DOF>
subvector(const vectview<const Scalar, BaseDOF> cvec, SubManifold<T, idx, dim> Base::* ptr)
{
return subvector_impl(cvec, ptr);
}
} // namespace MTK
#endif // GET_START_INDEX_H_
+316
View File
@@ -0,0 +1,316 @@
// This is a NEW implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/types/S2.hpp
* @brief Unit vectors on the sphere, or directions in 3D.
*/
#ifndef S2_H_
#define S2_H_
#include "vect.hpp"
#include "SOn.hpp"
#include "../src/mtkmath.hpp"
namespace MTK {
/**
* Manifold representation of @f$ S^2 @f$.
* Used for unit vectors on the sphere or directions in 3D.
*
* @todo add conversions from/to polar angles?
*/
template<class _scalar = double, int den = 1, int num = 1, int S2_typ = 3>
struct S2 {
typedef _scalar scalar;
typedef vect<3, scalar> vect_type;
typedef SO3<scalar> SO3_type;
typedef typename vect_type::base vec3;
scalar length = scalar(den)/scalar(num);
enum {DOF=2, TYP = 1, DIM = 3};
//private:
/**
* Unit vector on the sphere, or vector pointing in a direction
*/
vect_type vec;
public:
S2() {
if(S2_typ == 3) vec=length * vec3(0, 0, std::sqrt(1));
if(S2_typ == 2) vec=length * vec3(0, std::sqrt(1), 0);
if(S2_typ == 1) vec=length * vec3(std::sqrt(1), 0, 0);
}
S2(const scalar &x, const scalar &y, const scalar &z) : vec(vec3(x, y, z)) {
vec.normalize();
vec = vec * length;
}
S2(const vect_type &_vec) : vec(_vec) {
vec.normalize();
vec = vec * length;
}
void oplus(MTK::vectview<const scalar, 3> delta, scalar scale = 1)
{
SO3_type res;
res.w() = MTK::exp<scalar, 3>(res.vec(), delta, scalar(scale/2));
vec = res.toRotationMatrix() * vec;
}
void boxplus(MTK::vectview<const scalar, 2> delta, scalar scale=1) {
Eigen::Matrix<scalar, 3, 2> Bx;
S2_Bx(Bx);
vect_type Bu = Bx*delta;SO3_type res;
res.w() = MTK::exp<scalar, 3>(res.vec(), Bu, scalar(scale/2));
vec = res.toRotationMatrix() * vec;
}
void boxminus(MTK::vectview<scalar, 2> res, const S2<scalar, den, num, S2_typ>& other) const {
scalar v_sin = (MTK::hat(vec)*other.vec).norm();
scalar v_cos = vec.transpose() * other.vec;
scalar theta = std::atan2(v_sin, v_cos);
if(v_sin < MTK::tolerance<scalar>())
{
if(std::fabs(theta) > MTK::tolerance<scalar>() )
{
res[0] = 3.1415926;
res[1] = 0;
}
else{
res[0] = 0;
res[1] = 0;
}
}
else
{
S2<scalar, den, num, S2_typ> other_copy = other;
Eigen::Matrix<scalar, 3, 2>Bx;
other_copy.S2_Bx(Bx);
res = theta/v_sin * Bx.transpose() * MTK::hat(other.vec)*vec;
}
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
Eigen::Matrix<scalar, 3, 3> skew_vec;
skew_vec << scalar(0), -vec[2], vec[1],
vec[2], scalar(0), -vec[0],
-vec[1], vec[0], scalar(0);
res = skew_vec;
}
void S2_Bx(Eigen::Matrix<scalar, 3, 2> &res)
{
if(S2_typ == 3)
{
if(vec[2] + length > tolerance<scalar>())
{
res << length - vec[0]*vec[0]/(length+vec[2]), -vec[0]*vec[1]/(length+vec[2]),
-vec[0]*vec[1]/(length+vec[2]), length-vec[1]*vec[1]/(length+vec[2]),
-vec[0], -vec[1];
res /= length;
}
else
{
res = Eigen::Matrix<scalar, 3, 2>::Zero();
res(1, 1) = -1;
res(2, 0) = 1;
}
}
else if(S2_typ == 2)
{
if(vec[1] + length > tolerance<scalar>())
{
res << length - vec[0]*vec[0]/(length+vec[1]), -vec[0]*vec[2]/(length+vec[1]),
-vec[0], -vec[2],
-vec[0]*vec[2]/(length+vec[1]), length-vec[2]*vec[2]/(length+vec[1]);
res /= length;
}
else
{
res = Eigen::Matrix<scalar, 3, 2>::Zero();
res(1, 1) = -1;
res(2, 0) = 1;
}
}
else
{
if(vec[0] + length > tolerance<scalar>())
{
res << -vec[1], -vec[2],
length - vec[1]*vec[1]/(length+vec[0]), -vec[2]*vec[1]/(length+vec[0]),
-vec[2]*vec[1]/(length+vec[0]), length-vec[2]*vec[2]/(length+vec[0]);
res /= length;
}
else
{
res = Eigen::Matrix<scalar, 3, 2>::Zero();
res(1, 1) = -1;
res(2, 0) = 1;
}
}
}
void S2_Nx(Eigen::Matrix<scalar, 2, 3> &res, S2<scalar, den, num, S2_typ>& subtrahend)
{
if((vec+subtrahend.vec).norm() > tolerance<scalar>())
{
Eigen::Matrix<scalar, 3, 2> Bx;
S2_Bx(Bx);
if((vec-subtrahend.vec).norm() > tolerance<scalar>())
{
scalar v_sin = (MTK::hat(vec)*subtrahend.vec).norm();
scalar v_cos = vec.transpose() * subtrahend.vec;
res = Bx.transpose() * (std::atan2(v_sin, v_cos)/v_sin*MTK::hat(vec)+MTK::hat(vec)*subtrahend.vec*((-v_cos/v_sin/v_sin/length/length/length/length+std::atan2(v_sin, v_cos)/v_sin/v_sin/v_sin)*subtrahend.vec.transpose()*MTK::hat(vec)*MTK::hat(vec)-vec.transpose()/length/length/length/length));
}
else
{
res = 1/length/length*Bx.transpose()*MTK::hat(vec);
}
}
else
{
std::cerr << "No N(x, y) for x=-y" << std::endl;
std::exit(100);
}
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
Eigen::Matrix<scalar, 3, 2> Bx;
S2_Bx(Bx);
res = 1/length/length*Bx.transpose()*MTK::hat(vec);
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
Eigen::Matrix<scalar, 3, 2> Bx;
S2_Bx(Bx);
if(delta.norm() < tolerance<scalar>())
{
res = -MTK::hat(vec)*Bx;
}
else{
vect_type Bu = Bx*delta;
SO3_type exp_delta;
exp_delta.w() = MTK::exp<scalar, 3>(exp_delta.vec(), Bu, scalar(1/2));
res = -exp_delta.toRotationMatrix()*MTK::hat(vec)*MTK::A_matrix(Bu).transpose()*Bx;
}
}
operator const vect_type&() const{
return vec;
}
const vect_type& get_vect() const {
return vec;
}
friend S2<scalar, den, num, S2_typ> operator*(const SO3<scalar>& rot, const S2<scalar, den, num, S2_typ>& dir)
{
S2<scalar, den, num, S2_typ> ret;
ret.vec = rot * dir.vec;
return ret;
}
scalar operator[](int idx) const {return vec[idx]; }
friend std::ostream& operator<<(std::ostream &os, const S2<scalar, den, num, S2_typ>& vec){
return os << vec.vec.transpose() << " ";
}
friend std::istream& operator>>(std::istream &is, S2<scalar, den, num, S2_typ>& vec){
for(int i=0; i<3; ++i)
is >> vec.vec[i];
vec.vec.normalize();
vec.vec = vec.vec * vec.length;
return is;
}
};
} // namespace MTK
#endif /*S2_H_*/
+317
View File
@@ -0,0 +1,317 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/types/SOn.hpp
* @brief Standard Orthogonal Groups i.e.\ rotatation groups.
*/
#ifndef SON_H_
#define SON_H_
#include <Eigen/Geometry>
#include "vect.hpp"
#include "../src/mtkmath.hpp"
namespace MTK {
/**
* Two-dimensional orientations represented as scalar.
* There is no guarantee that the representing scalar is within any interval,
* but the result of boxminus will always have magnitude @f$\le\pi @f$.
*/
template<class _scalar = double, int Options = Eigen::AutoAlign>
struct SO2 : public Eigen::Rotation2D<_scalar> {
enum {DOF = 1, DIM = 2, TYP = 3};
typedef _scalar scalar;
typedef Eigen::Rotation2D<scalar> base;
typedef vect<DIM, scalar, Options> vect_type;
//! Construct from angle
SO2(const scalar& angle = 0) : base(angle) { }
//! Construct from Eigen::Rotation2D
SO2(const base& src) : base(src) {}
/**
* Construct from 2D vector.
* Resulting orientation will rotate the first unit vector to point to vec.
*/
SO2(const vect_type &vec) : base(atan2(vec[1], vec[0])) {};
//! Calculate @c this->inverse() * @c r
SO2 operator%(const base &r) const {
return base::inverse() * r;
}
//! Calculate @c this->inverse() * @c r
template<class Derived>
vect_type operator%(const Eigen::MatrixBase<Derived> &vec) const {
return base::inverse() * vec;
}
//! Calculate @c *this * @c r.inverse()
SO2 operator/(const SO2 &r) const {
return *this * r.inverse();
}
//! Gets the angle as scalar.
operator scalar() const {
return base::angle();
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
//! @name Manifold requirements
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
base::angle() += scale * vec[0];
}
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
base::angle() += scale * vec[0];
}
void boxminus(MTK::vectview<scalar, DOF> res, const SO2<scalar>& other) const {
res[0] = MTK::normalize(base::angle() - other.angle(), scalar(MTK::pi));
}
friend std::istream& operator>>(std::istream &is, SO2<scalar>& ang){
return is >> ang.angle();
}
};
/**
* Three-dimensional orientations represented as Quaternion.
* It is assumed that the internal Quaternion always stays normalized,
* should this not be the case, call inherited member function @c normalize().
*/
template<class _scalar = double, int Options = Eigen::AutoAlign>
struct SO3 : public Eigen::Quaternion<_scalar, Options> {
enum {DOF = 3, DIM = 3, TYP = 2};
typedef _scalar scalar;
typedef Eigen::Quaternion<scalar, Options> base;
typedef Eigen::Quaternion<scalar> Quaternion;
typedef vect<DIM, scalar, Options> vect_type;
//! Calculate @c this->inverse() * @c r
template<class OtherDerived> EIGEN_STRONG_INLINE
Quaternion operator%(const Eigen::QuaternionBase<OtherDerived> &r) const {
return base::conjugate() * r;
}
//! Calculate @c this->inverse() * @c r
template<class Derived>
vect_type operator%(const Eigen::MatrixBase<Derived> &vec) const {
return base::conjugate() * vec;
}
//! Calculate @c this * @c r.conjugate()
template<class OtherDerived> EIGEN_STRONG_INLINE
Quaternion operator/(const Eigen::QuaternionBase<OtherDerived> &r) const {
return *this * r.conjugate();
}
/**
* Construct from real part and three imaginary parts.
* Quaternion is normalized after construction.
*/
SO3(const scalar& w, const scalar& x, const scalar& y, const scalar& z) : base(w, x, y, z) {
base::normalize();
}
/**
* Construct from Eigen::Quaternion.
* @note Non-normalized input may result result in spurious behavior.
*/
SO3(const base& src = base::Identity()) : base(src) {}
/**
* Construct from rotation matrix.
* @note Invalid rotation matrices may lead to spurious behavior.
*/
template<class Derived>
SO3(const Eigen::MatrixBase<Derived>& matrix) : base(matrix) {}
/**
* Construct from arbitrary rotation type.
* @note Invalid rotation matrices may lead to spurious behavior.
*/
template<class Derived>
SO3(const Eigen::RotationBase<Derived, 3>& rotation) : base(rotation.derived()) {}
//! @name Manifold requirements
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale=1) {
SO3 delta = exp(vec, scale);
*this = *this * delta;
}
void boxminus(MTK::vectview<scalar, DOF> res, const SO3<scalar>& other) const {
res = SO3::log(other.conjugate() * *this);
}
//}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale=1) {
SO3 delta = exp(vec, scale);
*this = *this * delta;
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
friend std::ostream& operator<<(std::ostream &os, const SO3<scalar, Options>& q){
return os << q.coeffs().transpose() << " ";
}
friend std::istream& operator>>(std::istream &is, SO3<scalar, Options>& q){
vect<4,scalar> coeffs;
is >> coeffs;
q.coeffs() = coeffs.normalized();
return is;
}
//! @name Helper functions
//{
/**
* Calculate the exponential map. In matrix terms this would correspond
* to the Rodrigues formula.
*/
// FIXME vectview<> can't be constructed from every MatrixBase<>, use const Vector3x& as workaround
// static SO3 exp(MTK::vectview<const scalar, 3> dvec, scalar scale = 1){
static SO3 exp(const Eigen::Matrix<scalar, 3, 1>& dvec, scalar scale = 1){
SO3 res;
res.w() = MTK::exp<scalar, 3>(res.vec(), dvec, scalar(scale/2));
return res;
}
/**
* Calculate the inverse of @c exp.
* Only guarantees that <code>exp(log(x)) == x </code>
*/
static typename base::Vector3 log(const SO3 &orient){
typename base::Vector3 res;
MTK::log<scalar, 3>(res, orient.w(), orient.vec(), scalar(2), true);
return res;
}
};
namespace internal {
template<class Scalar, int Options>
struct UnalignedType<SO2<Scalar, Options > >{
typedef SO2<Scalar, Options | Eigen::DontAlign> type;
};
template<class Scalar, int Options>
struct UnalignedType<SO3<Scalar, Options > >{
typedef SO3<Scalar, Options | Eigen::DontAlign> type;
};
} // namespace internal
} // namespace MTK
#endif /*SON_H_*/
+461
View File
@@ -0,0 +1,461 @@
// This is an advanced implementation of the algorithm described in the
// following paper:
// C. Hertzberg, R. Wagner, U. Frese, and L. Schroder. Integratinggeneric sensor fusion algorithms with sound state representationsthrough encapsulation of manifolds.
// CoRR, vol. abs/1107.1119, 2011.[Online]. Available: http://arxiv.org/abs/1107.1119
/*
* Copyright (c) 2019--2023, The University of Hong Kong
* All rights reserved.
*
* Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
*
* 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 Universitaet Bremen 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.
*/
/*
* Copyright (c) 2008--2011, Universitaet Bremen
* All rights reserved.
*
* Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen 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.
*/
/**
* @file mtk/types/vect.hpp
* @brief Basic vectors interpreted as manifolds.
*
* This file also implements a simple wrapper for matrices, for arbitrary scalars
* and for positive scalars.
*/
#ifndef VECT_H_
#define VECT_H_
#include <iosfwd>
#include <iostream>
#include <vector>
#include "../src/vectview.hpp"
namespace MTK {
static const Eigen::IOFormat IO_no_spaces(Eigen::StreamPrecision, Eigen::DontAlignCols, ",", ",", "", "", "[", "]");
/**
* A simple vector class.
* Implementation is basically a wrapper around Eigen::Matrix with manifold
* requirements added.
*/
template<int D = 3, class _scalar = double, int _Options=Eigen::AutoAlign>
struct vect : public Eigen::Matrix<_scalar, D, 1, _Options> {
typedef Eigen::Matrix<_scalar, D, 1, _Options> base;
enum {DOF = D, DIM = D, TYP = 0};
typedef _scalar scalar;
//using base::operator=;
/** Standard constructor. Sets all values to zero. */
vect(const base &src = base::Zero()) : base(src) {}
/** Constructor copying the value of the expression \a other */
template<typename OtherDerived>
EIGEN_STRONG_INLINE vect(const Eigen::DenseBase<OtherDerived>& other) : base(other) {}
/** Construct from memory. */
vect(const scalar* src, int size = DOF) : base(base::Map(src, size)) { }
void boxplus(MTK::vectview<const scalar, D> vec, scalar scale=1) {
*this += scale * vec;
}
void boxminus(MTK::vectview<scalar, D> res, const vect<D, scalar>& other) const {
res = *this - other;
}
void oplus(MTK::vectview<const scalar, D> vec, scalar scale=1) {
*this += scale * vec;
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
friend std::ostream& operator<<(std::ostream &os, const vect<D, scalar, _Options>& v){
// Eigen sometimes messes with the streams flags, so output manually:
for(int i=0; i<DOF; ++i)
os << v(i) << " ";
return os;
}
friend std::istream& operator>>(std::istream &is, vect<D, scalar, _Options>& v){
char term=0;
is >> std::ws; // skip whitespace
switch(is.peek()) {
case '(': term=')'; is.ignore(1); break;
case '[': term=']'; is.ignore(1); break;
case '{': term='}'; is.ignore(1); break;
default: break;
}
if(D==Eigen::Dynamic) {
assert(term !=0 && "Dynamic vectors must be embraced");
std::vector<scalar> temp;
while(is.good() && is.peek() != term) {
scalar x;
is >> x;
temp.push_back(x);
if(is.peek()==',') is.ignore(1);
}
v = vect::Map(temp.data(), temp.size());
} else
for(int i=0; i<v.size(); ++i){
is >> v[i];
if(is.peek()==',') { // ignore commas between values
is.ignore(1);
}
}
if(term!=0) {
char x;
is >> x;
if(x!=term) {
is.setstate(is.badbit);
// assert(x==term && "start and end bracket do not match!");
}
}
return is;
}
template<int dim>
vectview<scalar, dim> tail(){
BOOST_STATIC_ASSERT(0< dim && dim <= DOF);
return base::template tail<dim>();
}
template<int dim>
vectview<const scalar, dim> tail() const{
BOOST_STATIC_ASSERT(0< dim && dim <= DOF);
return base::template tail<dim>();
}
template<int dim>
vectview<scalar, dim> head(){
BOOST_STATIC_ASSERT(0< dim && dim <= DOF);
return base::template head<dim>();
}
template<int dim>
vectview<const scalar, dim> head() const{
BOOST_STATIC_ASSERT(0< dim && dim <= DOF);
return base::template head<dim>();
}
};
/**
* A simple matrix class.
* Implementation is basically a wrapper around Eigen::Matrix with manifold
* requirements added, i.e., matrix is viewed as a plain vector for that.
*/
template<int M, int N, class _scalar = double, int _Options = Eigen::Matrix<_scalar, M, N>::Options>
struct matrix : public Eigen::Matrix<_scalar, M, N, _Options> {
typedef Eigen::Matrix<_scalar, M, N, _Options> base;
enum {DOF = M * N, TYP = 4, DIM=0};
typedef _scalar scalar;
using base::operator=;
/** Standard constructor. Sets all values to zero. */
matrix() {
base::setZero();
}
/** Constructor copying the value of the expression \a other */
template<typename OtherDerived>
EIGEN_STRONG_INLINE matrix(const Eigen::MatrixBase<OtherDerived>& other) : base(other) {}
/** Construct from memory. */
matrix(const scalar* src) : base(src) { }
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
*this += scale * base::Map(vec.data());
}
void boxminus(MTK::vectview<scalar, DOF> res, const matrix& other) const {
base::Map(res.data()) = *this - other;
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
*this += scale * base::Map(vec.data());
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
friend std::ostream& operator<<(std::ostream &os, const matrix<M, N, scalar, _Options>& mat){
for(int i=0; i<DOF; ++i){
os << mat.data()[i] << " ";
}
return os;
}
friend std::istream& operator>>(std::istream &is, matrix<M, N, scalar, _Options>& mat){
for(int i=0; i<DOF; ++i){
is >> mat.data()[i];
}
return is;
}
};// @todo What if M / N = Eigen::Dynamic?
/**
* A simple scalar type.
*/
template<class _scalar = double>
struct Scalar {
enum {DOF = 1, TYP = 5, DIM=0};
typedef _scalar scalar;
scalar value;
Scalar(const scalar& value = scalar(0)) : value(value) {}
operator const scalar&() const { return value; }
operator scalar&() { return value; }
Scalar& operator=(const scalar& val) { value = val; return *this; }
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale=1) {
value += scale * vec[0];
}
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale=1) {
value += scale * vec[0];
}
void boxminus(MTK::vectview<scalar, DOF> res, const Scalar& other) const {
res[0] = *this - other;
}
};
/**
* Positive scalars.
* Boxplus is implemented using multiplication by @f$x\boxplus\delta = x\cdot\exp(\delta) @f$.
*/
template<class _scalar = double>
struct PositiveScalar {
enum {DOF = 1, TYP = 6, DIM=0};
typedef _scalar scalar;
scalar value;
PositiveScalar(const scalar& value = scalar(1)) : value(value) {
assert(value > scalar(0));
}
operator const scalar&() const { return value; }
PositiveScalar& operator=(const scalar& val) { assert(val>0); value = val; return *this; }
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
value *= std::exp(scale * vec[0]);
}
void boxminus(MTK::vectview<scalar, DOF> res, const PositiveScalar& other) const {
res[0] = std::log(*this / other);
}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
value *= std::exp(scale * vec[0]);
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
friend std::istream& operator>>(std::istream &is, PositiveScalar<scalar>& s){
is >> s.value;
assert(s.value > 0);
return is;
}
};
template<class _scalar = double>
struct Complex : public std::complex<_scalar>{
enum {DOF = 2, TYP = 7, DIM=0};
typedef _scalar scalar;
typedef std::complex<scalar> Base;
Complex(const Base& value) : Base(value) {}
Complex(const scalar& re = 0.0, const scalar& im = 0.0) : Base(re, im) {}
Complex(const MTK::vectview<const scalar, 2> &in) : Base(in[0], in[1]) {}
template<class Derived>
Complex(const Eigen::DenseBase<Derived> &in) : Base(in[0], in[1]) {}
void boxplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
Base::real() += scale * vec[0];
Base::imag() += scale * vec[1];
};
void boxminus(MTK::vectview<scalar, DOF> res, const Complex& other) const {
Complex diff = *this - other;
res << diff.real(), diff.imag();
}
void S2_hat(Eigen::Matrix<scalar, 3, 3> &res)
{
res = Eigen::Matrix<scalar, 3, 3>::Zero();
}
void oplus(MTK::vectview<const scalar, DOF> vec, scalar scale = 1) {
Base::real() += scale * vec[0];
Base::imag() += scale * vec[1];
};
void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3> &res)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 2, 3>::Zero();
}
void S2_Mx(Eigen::Matrix<scalar, 3, 2> &res, MTK::vectview<const scalar, 2> delta)
{
std::cerr << "wrong idx for S2" << std::endl;
std::exit(100);
res = Eigen::Matrix<scalar, 3, 2>::Zero();
}
scalar squaredNorm() const {
return std::pow(Base::real(),2) + std::pow(Base::imag(),2);
}
const scalar& operator()(int i) const {
assert(0<=i && i<2 && "Index out of range");
return i==0 ? Base::real() : Base::imag();
}
scalar& operator()(int i){
assert(0<=i && i<2 && "Index out of range");
return i==0 ? Base::real() : Base::imag();
}
};
namespace internal {
template<int dim, class Scalar, int Options>
struct UnalignedType<vect<dim, Scalar, Options > >{
typedef vect<dim, Scalar, Options | Eigen::DontAlign> type;
};
} // namespace internal
} // namespace MTK
#endif /*VECT_H_*/
+113
View File
@@ -0,0 +1,113 @@
/*
* Copyright (c) 2010--2011, Universitaet Bremen and DFKI GmbH
* All rights reserved.
*
* Author: Rene Wagner <rene.wagner@dfki.de>
* Christoph Hertzberg <chtz@informatik.uni-bremen.de>
*
* 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 Universitaet Bremen nor the DFKI GmbH
* 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.
*/
#ifndef WRAPPED_CV_MAT_HPP_
#define WRAPPED_CV_MAT_HPP_
#include <Eigen/Core>
#include <opencv/cv.h>
namespace MTK {
template<class f_type>
struct cv_f_type;
template<>
struct cv_f_type<double>
{
enum {value = CV_64F};
};
template<>
struct cv_f_type<float>
{
enum {value = CV_32F};
};
/**
* cv_mat wraps a CvMat around an Eigen Matrix
*/
template<int rows, int cols, class f_type = double>
class cv_mat : public matrix<rows, cols, f_type, cols==1 ? Eigen::ColMajor : Eigen::RowMajor>
{
typedef matrix<rows, cols, f_type, cols==1 ? Eigen::ColMajor : Eigen::RowMajor> base_type;
enum {type_ = cv_f_type<f_type>::value};
CvMat cv_mat_;
public:
cv_mat()
{
cv_mat_ = cvMat(rows, cols, type_, base_type::data());
}
cv_mat(const cv_mat& oth) : base_type(oth)
{
cv_mat_ = cvMat(rows, cols, type_, base_type::data());
}
template<class Derived>
cv_mat(const Eigen::MatrixBase<Derived> &value) : base_type(value)
{
cv_mat_ = cvMat(rows, cols, type_, base_type::data());
}
template<class Derived>
cv_mat& operator=(const Eigen::MatrixBase<Derived> &value)
{
base_type::operator=(value);
return *this;
}
cv_mat& operator=(const cv_mat& value)
{
base_type::operator=(value);
return *this;
}
// FIXME: Maybe overloading operator& is not a good idea ...
CvMat* operator&()
{
return &cv_mat_;
}
const CvMat* operator&() const
{
return &cv_mat_;
}
};
} // namespace MTK
#endif /* WRAPPED_CV_MAT_HPP_ */
+270
View File
@@ -0,0 +1,270 @@
#ifndef COMMON_LIB_H
#define COMMON_LIB_H
#include <so3_math.h>
#include <Eigen/Eigen>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <fast_lio/msg/pose6_d.hpp>
#include <sensor_msgs/msg/imu.hpp>
#include <nav_msgs/msg/odometry.hpp>
using namespace std;
using namespace Eigen;
#define USE_IKFOM
#define PI_M (3.14159265358)
#define G_m_s2 (9.81) // Gravaty const in GuangDong/China
#define DIM_STATE (18) // Dimension of states (Let Dim(SO(3)) = 3)
#define DIM_PROC_N (12) // Dimension of process noise (Let Dim(SO(3)) = 3)
#define CUBE_LEN (6.0)
#define LIDAR_SP_LEN (2)
#define INIT_COV (1)
#define NUM_MATCH_POINTS (5)
#define MAX_MEAS_DIM (10000)
#define VEC_FROM_ARRAY(v) v[0],v[1],v[2]
#define MAT_FROM_ARRAY(v) v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8]
#define CONSTRAIN(v,min,max) ((v>min)?((v<max)?v:max):min)
#define ARRAY_FROM_EIGEN(mat) mat.data(), mat.data() + mat.rows() * mat.cols()
#define STD_VEC_FROM_EIGEN(mat) vector<decltype(mat)::Scalar> (mat.data(), mat.data() + mat.rows() * mat.cols())
#define DEBUG_FILE_DIR(name) (string(string(ROOT_DIR) + "Log/"+ name))
typedef fast_lio::msg::Pose6D Pose6D;
typedef pcl::PointXYZINormal PointType;
typedef pcl::PointCloud<PointType> PointCloudXYZI;
typedef vector<PointType, Eigen::aligned_allocator<PointType>> PointVector;
typedef Vector3d V3D;
typedef Matrix3d M3D;
typedef Vector3f V3F;
typedef Matrix3f M3F;
#define MD(a,b) Matrix<double, (a), (b)>
#define VD(a) Matrix<double, (a), 1>
#define MF(a,b) Matrix<float, (a), (b)>
#define VF(a) Matrix<float, (a), 1>
M3D Eye3d(M3D::Identity());
M3F Eye3f(M3F::Identity());
V3D Zero3d(0, 0, 0);
V3F Zero3f(0, 0, 0);
struct MeasureGroup // Lidar data and imu dates for the curent process
{
MeasureGroup()
{
lidar_beg_time = 0.0;
this->lidar.reset(new PointCloudXYZI());
};
double lidar_beg_time;
double lidar_end_time;
PointCloudXYZI::Ptr lidar;
deque<sensor_msgs::msg::Imu::ConstSharedPtr> imu;
};
struct StatesGroup
{
StatesGroup() {
this->rot_end = M3D::Identity();
this->pos_end = Zero3d;
this->vel_end = Zero3d;
this->bias_g = Zero3d;
this->bias_a = Zero3d;
this->gravity = Zero3d;
this->cov = MD(DIM_STATE,DIM_STATE)::Identity() * INIT_COV;
this->cov.block<9,9>(9,9) = MD(9,9)::Identity() * 0.00001;
};
StatesGroup(const StatesGroup& b) {
this->rot_end = b.rot_end;
this->pos_end = b.pos_end;
this->vel_end = b.vel_end;
this->bias_g = b.bias_g;
this->bias_a = b.bias_a;
this->gravity = b.gravity;
this->cov = b.cov;
};
StatesGroup& operator=(const StatesGroup& b)
{
this->rot_end = b.rot_end;
this->pos_end = b.pos_end;
this->vel_end = b.vel_end;
this->bias_g = b.bias_g;
this->bias_a = b.bias_a;
this->gravity = b.gravity;
this->cov = b.cov;
return *this;
};
StatesGroup operator+(const Matrix<double, DIM_STATE, 1> &state_add)
{
StatesGroup a;
a.rot_end = this->rot_end * Exp(state_add(0,0), state_add(1,0), state_add(2,0));
a.pos_end = this->pos_end + state_add.block<3,1>(3,0);
a.vel_end = this->vel_end + state_add.block<3,1>(6,0);
a.bias_g = this->bias_g + state_add.block<3,1>(9,0);
a.bias_a = this->bias_a + state_add.block<3,1>(12,0);
a.gravity = this->gravity + state_add.block<3,1>(15,0);
a.cov = this->cov;
return a;
};
StatesGroup& operator+=(const Matrix<double, DIM_STATE, 1> &state_add)
{
this->rot_end = this->rot_end * Exp(state_add(0,0), state_add(1,0), state_add(2,0));
this->pos_end += state_add.block<3,1>(3,0);
this->vel_end += state_add.block<3,1>(6,0);
this->bias_g += state_add.block<3,1>(9,0);
this->bias_a += state_add.block<3,1>(12,0);
this->gravity += state_add.block<3,1>(15,0);
return *this;
};
Matrix<double, DIM_STATE, 1> operator-(const StatesGroup& b)
{
Matrix<double, DIM_STATE, 1> a;
M3D rotd(b.rot_end.transpose() * this->rot_end);
a.block<3,1>(0,0) = Log(rotd);
a.block<3,1>(3,0) = this->pos_end - b.pos_end;
a.block<3,1>(6,0) = this->vel_end - b.vel_end;
a.block<3,1>(9,0) = this->bias_g - b.bias_g;
a.block<3,1>(12,0) = this->bias_a - b.bias_a;
a.block<3,1>(15,0) = this->gravity - b.gravity;
return a;
};
void resetpose()
{
this->rot_end = M3D::Identity();
this->pos_end = Zero3d;
this->vel_end = Zero3d;
}
M3D rot_end; // the estimated attitude (rotation matrix) at the end lidar point
V3D pos_end; // the estimated position at the end lidar point (world frame)
V3D vel_end; // the estimated velocity at the end lidar point (world frame)
V3D bias_g; // gyroscope bias
V3D bias_a; // accelerator bias
V3D gravity; // the estimated gravity acceleration
Matrix<double, DIM_STATE, DIM_STATE> cov; // states covariance
};
template<typename T>
T rad2deg(T radians)
{
return radians * 180.0 / PI_M;
}
template<typename T>
T deg2rad(T degrees)
{
return degrees * PI_M / 180.0;
}
template<typename T>
auto set_pose6d(const double t, const Matrix<T, 3, 1> &a, const Matrix<T, 3, 1> &g, \
const Matrix<T, 3, 1> &v, const Matrix<T, 3, 1> &p, const Matrix<T, 3, 3> &R)
{
Pose6D rot_kp;
rot_kp.offset_time = t;
for (int i = 0; i < 3; i++)
{
rot_kp.acc[i] = a(i);
rot_kp.gyr[i] = g(i);
rot_kp.vel[i] = v(i);
rot_kp.pos[i] = p(i);
for (int j = 0; j < 3; j++) rot_kp.rot[i*3+j] = R(i,j);
}
return move(rot_kp);
}
/* comment
plane equation: Ax + By + Cz + D = 0
convert to: A/D*x + B/D*y + C/D*z = -1
solve: A0*x0 = b0
where A0_i = [x_i, y_i, z_i], x0 = [A/D, B/D, C/D]^T, b0 = [-1, ..., -1]^T
normvec: normalized x0
*/
template<typename T>
bool esti_normvector(Matrix<T, 3, 1> &normvec, const PointVector &point, const T &threshold, const int &point_num)
{
MatrixXf A(point_num, 3);
MatrixXf b(point_num, 1);
b.setOnes();
b *= -1.0f;
for (int j = 0; j < point_num; j++)
{
A(j,0) = point[j].x;
A(j,1) = point[j].y;
A(j,2) = point[j].z;
}
normvec = A.colPivHouseholderQr().solve(b);
for (int j = 0; j < point_num; j++)
{
if (fabs(normvec(0) * point[j].x + normvec(1) * point[j].y + normvec(2) * point[j].z + 1.0f) > threshold)
{
return false;
}
}
normvec.normalize();
return true;
}
float calc_dist(PointType p1, PointType p2){
float d = (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) + (p1.z - p2.z) * (p1.z - p2.z);
return d;
}
template<typename T>
bool esti_plane(Matrix<T, 4, 1> &pca_result, const PointVector &point, const T &threshold)
{
Matrix<T, NUM_MATCH_POINTS, 3> A;
Matrix<T, NUM_MATCH_POINTS, 1> b;
A.setZero();
b.setOnes();
b *= -1.0f;
for (int j = 0; j < NUM_MATCH_POINTS; j++)
{
A(j,0) = point[j].x;
A(j,1) = point[j].y;
A(j,2) = point[j].z;
}
Matrix<T, 3, 1> normvec = A.colPivHouseholderQr().solve(b);
T n = normvec.norm();
pca_result(0) = normvec(0) / n;
pca_result(1) = normvec(1) / n;
pca_result(2) = normvec(2) / n;
pca_result(3) = 1.0 / n;
for (int j = 0; j < NUM_MATCH_POINTS; j++)
{
if (fabs(pca_result(0) * point[j].x + pca_result(1) * point[j].y + pca_result(2) * point[j].z + pca_result(3)) > threshold)
{
return false;
}
}
return true;
}
double get_time_sec(const builtin_interfaces::msg::Time &time)
{
return rclcpp::Time(time).seconds();
}
rclcpp::Time get_ros_time(double timestamp)
{
int32_t sec = std::floor(timestamp);
auto nanosec_d = (timestamp - std::floor(timestamp)) * 1e9;
uint32_t nanosec = nanosec_d;
return rclcpp::Time(sec, nanosec);
}
#endif
+2
View File
@@ -0,0 +1,2 @@
# ikd-Tree
ikd-Tree is an incremental k-d tree for robotic applications.
File diff suppressed because it is too large Load Diff
+344
View File
@@ -0,0 +1,344 @@
#pragma once
#include <stdio.h>
#include <queue>
#include <pthread.h>
#include <chrono>
#include <time.h>
#include <unistd.h>
#include <math.h>
#include <algorithm>
#include <memory.h>
#include <pcl/point_types.h>
#define EPSS 1e-6
#define Minimal_Unbalanced_Tree_Size 10
#define Multi_Thread_Rebuild_Point_Num 1500
#define DOWNSAMPLE_SWITCH true
#define ForceRebuildPercentage 0.2
#define Q_LEN 1000000
using namespace std;
// typedef pcl::PointXYZINormal PointType;
// typedef vector<PointType, Eigen::aligned_allocator<PointType>> PointVector;
struct BoxPointType
{
float vertex_min[3];
float vertex_max[3];
};
enum operation_set
{
ADD_POINT,
DELETE_POINT,
DELETE_BOX,
ADD_BOX,
DOWNSAMPLE_DELETE,
PUSH_DOWN
};
enum delete_point_storage_set
{
NOT_RECORD,
DELETE_POINTS_REC,
MULTI_THREAD_REC
};
template <typename PointType>
class KD_TREE
{
// using MANUAL_Q_ = MANUAL_Q<typename PointType>;
// using PointVector = std::vector<PointType>;
// using MANUAL_Q_ = MANUAL_Q<typename PointType>;
public:
using PointVector = std::vector<PointType, Eigen::aligned_allocator<PointType>>;
using Ptr = std::shared_ptr<KD_TREE<PointType>>;
struct KD_TREE_NODE
{
PointType point;
int division_axis;
int TreeSize = 1;
int invalid_point_num = 0;
int down_del_num = 0;
bool point_deleted = false;
bool tree_deleted = false;
bool point_downsample_deleted = false;
bool tree_downsample_deleted = false;
bool need_push_down_to_left = false;
bool need_push_down_to_right = false;
bool working_flag = false;
pthread_mutex_t push_down_mutex_lock;
float node_range_x[2], node_range_y[2], node_range_z[2];
float radius_sq;
KD_TREE_NODE *left_son_ptr = nullptr;
KD_TREE_NODE *right_son_ptr = nullptr;
KD_TREE_NODE *father_ptr = nullptr;
// For paper data record
float alpha_del;
float alpha_bal;
};
struct Operation_Logger_Type
{
PointType point;
BoxPointType boxpoint;
bool tree_deleted, tree_downsample_deleted;
operation_set op;
};
// static const PointType zeroP;
struct PointType_CMP
{
PointType point;
float dist = 0.0;
PointType_CMP(PointType p = PointType(), float d = INFINITY)
{
this->point = p;
this->dist = d;
};
bool operator<(const PointType_CMP &a) const
{
if (fabs(dist - a.dist) < 1e-10)
return point.x < a.point.x;
else
return dist < a.dist;
}
};
class MANUAL_HEAP
{
public:
MANUAL_HEAP(int max_capacity = 100)
{
cap = max_capacity;
heap = new PointType_CMP[max_capacity];
heap_size = 0;
}
~MANUAL_HEAP()
{
delete[] heap;
}
void pop()
{
if (heap_size == 0)
return;
heap[0] = heap[heap_size - 1];
heap_size--;
MoveDown(0);
return;
}
PointType_CMP top()
{
return heap[0];
}
void push(PointType_CMP point)
{
if (heap_size >= cap)
return;
heap[heap_size] = point;
FloatUp(heap_size);
heap_size++;
return;
}
int size()
{
return heap_size;
}
void clear()
{
heap_size = 0;
return;
}
private:
PointType_CMP *heap;
void MoveDown(int heap_index)
{
int l = heap_index * 2 + 1;
PointType_CMP tmp = heap[heap_index];
while (l < heap_size)
{
if (l + 1 < heap_size && heap[l] < heap[l + 1])
l++;
if (tmp < heap[l])
{
heap[heap_index] = heap[l];
heap_index = l;
l = heap_index * 2 + 1;
}
else
break;
}
heap[heap_index] = tmp;
return;
}
void FloatUp(int heap_index)
{
int ancestor = (heap_index - 1) / 2;
PointType_CMP tmp = heap[heap_index];
while (heap_index > 0)
{
if (heap[ancestor] < tmp)
{
heap[heap_index] = heap[ancestor];
heap_index = ancestor;
ancestor = (heap_index - 1) / 2;
}
else
break;
}
heap[heap_index] = tmp;
return;
}
int heap_size = 0;
int cap = 0;
};
class MANUAL_Q
{
private:
int head = 0, tail = 0, counter = 0;
Operation_Logger_Type q[Q_LEN];
bool is_empty;
public:
void pop()
{
if (counter == 0)
return;
head++;
head %= Q_LEN;
counter--;
if (counter == 0)
is_empty = true;
return;
}
Operation_Logger_Type front()
{
return q[head];
}
Operation_Logger_Type back()
{
return q[tail];
}
void clear()
{
head = 0;
tail = 0;
counter = 0;
is_empty = true;
return;
}
void push(Operation_Logger_Type op)
{
q[tail] = op;
counter++;
if (is_empty)
is_empty = false;
tail++;
tail %= Q_LEN;
}
bool empty()
{
return is_empty;
}
int size()
{
return counter;
}
};
private:
// Multi-thread Tree Rebuild
bool termination_flag = false;
bool rebuild_flag = false;
pthread_t rebuild_thread;
pthread_mutex_t termination_flag_mutex_lock, rebuild_ptr_mutex_lock, working_flag_mutex, search_flag_mutex;
pthread_mutex_t rebuild_logger_mutex_lock, points_deleted_rebuild_mutex_lock;
// queue<Operation_Logger_Type> Rebuild_Logger;
MANUAL_Q Rebuild_Logger;
PointVector Rebuild_PCL_Storage;
KD_TREE_NODE **Rebuild_Ptr = nullptr;
int search_mutex_counter = 0;
static void *multi_thread_ptr(void *arg);
void multi_thread_rebuild();
void start_thread();
void stop_thread();
void run_operation(KD_TREE_NODE **root, Operation_Logger_Type operation);
// KD Tree Functions and augmented variables
int Treesize_tmp = 0, Validnum_tmp = 0;
float alpha_bal_tmp = 0.5, alpha_del_tmp = 0.0;
float delete_criterion_param = 0.5f;
float balance_criterion_param = 0.7f;
float downsample_size = 0.2f;
bool Delete_Storage_Disabled = false;
KD_TREE_NODE *STATIC_ROOT_NODE = nullptr;
PointVector Points_deleted;
PointVector Downsample_Storage;
PointVector Multithread_Points_deleted;
void InitTreeNode(KD_TREE_NODE *root);
void Test_Lock_States(KD_TREE_NODE *root);
void BuildTree(KD_TREE_NODE **root, int l, int r, PointVector &Storage);
void Rebuild(KD_TREE_NODE **root);
int Delete_by_range(KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild, bool is_downsample);
void Delete_by_point(KD_TREE_NODE **root, PointType point, bool allow_rebuild);
void Add_by_point(KD_TREE_NODE **root, PointType point, bool allow_rebuild, int father_axis);
void Add_by_range(KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild);
void Search(KD_TREE_NODE *root, int k_nearest, PointType point, MANUAL_HEAP &q, float max_dist); //priority_queue<PointType_CMP>
void Search_by_range(KD_TREE_NODE *root, BoxPointType boxpoint, PointVector &Storage);
void Search_by_radius(KD_TREE_NODE *root, PointType point, float radius, PointVector &Storage);
bool Criterion_Check(KD_TREE_NODE *root);
void Push_Down(KD_TREE_NODE *root);
void Update(KD_TREE_NODE *root);
void delete_tree_nodes(KD_TREE_NODE **root);
void downsample(KD_TREE_NODE **root);
bool same_point(PointType a, PointType b);
float calc_dist(PointType a, PointType b);
float calc_box_dist(KD_TREE_NODE *node, PointType point);
static bool point_cmp_x(PointType a, PointType b);
static bool point_cmp_y(PointType a, PointType b);
static bool point_cmp_z(PointType a, PointType b);
public:
KD_TREE(float delete_param = 0.5, float balance_param = 0.6, float box_length = 0.2);
~KD_TREE();
void Set_delete_criterion_param(float delete_param)
{
delete_criterion_param = delete_param;
}
void Set_balance_criterion_param(float balance_param)
{
balance_criterion_param = balance_param;
}
void set_downsample_param(float downsample_param)
{
downsample_size = downsample_param;
}
void InitializeKDTree(float delete_param = 0.5, float balance_param = 0.7, float box_length = 0.2);
int size();
int validnum();
void root_alpha(float &alpha_bal, float &alpha_del);
void Build(PointVector point_cloud);
void Nearest_Search(PointType point, int k_nearest, PointVector &Nearest_Points, vector<float> &Point_Distance, float max_dist = INFINITY);
void Box_Search(const BoxPointType &Box_of_Point, PointVector &Storage);
void Radius_Search(PointType point, const float radius, PointVector &Storage);
int Add_Points(PointVector &PointToAdd, bool downsample_on);
void Add_Point_Boxes(vector<BoxPointType> &BoxPoints);
void Delete_Points(PointVector &PointToDel);
int Delete_Point_Boxes(vector<BoxPointType> &BoxPoints);
void flatten(KD_TREE_NODE *root, PointVector &Storage, delete_point_storage_set storage_type);
void acquire_removed_points(PointVector &removed_points);
BoxPointType tree_range();
PointVector PCL_Storage;
KD_TREE_NODE *Root_Node = nullptr;
int max_queue_size = 0;
};
// template <typename PointType>
// PointType KD_TREE<PointType>::zeroP = PointType(0,0,0);
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
#ifndef SO3_MATH_H
#define SO3_MATH_H
#include <math.h>
#include <Eigen/Core>
#define SKEW_SYM_MATRX(v) 0.0,-v[2],v[1],v[2],0.0,-v[0],-v[1],v[0],0.0
template<typename T>
Eigen::Matrix<T, 3, 3> skew_sym_mat(const Eigen::Matrix<T, 3, 1> &v)
{
Eigen::Matrix<T, 3, 3> skew_sym_mat;
skew_sym_mat<<0.0,-v[2],v[1],v[2],0.0,-v[0],-v[1],v[0],0.0;
return skew_sym_mat;
}
template<typename T>
Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &&ang)
{
T ang_norm = ang.norm();
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (ang_norm > 0.0000001)
{
Eigen::Matrix<T, 3, 1> r_axis = ang / ang_norm;
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_axis);
/// Roderigous Tranformation
return Eye3 + std::sin(ang_norm) * K + (1.0 - std::cos(ang_norm)) * K * K;
}
else
{
return Eye3;
}
}
template<typename T, typename Ts>
Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &ang_vel, const Ts &dt)
{
T ang_vel_norm = ang_vel.norm();
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (ang_vel_norm > 0.0000001)
{
Eigen::Matrix<T, 3, 1> r_axis = ang_vel / ang_vel_norm;
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_axis);
T r_ang = ang_vel_norm * dt;
/// Roderigous Tranformation
return Eye3 + std::sin(r_ang) * K + (1.0 - std::cos(r_ang)) * K * K;
}
else
{
return Eye3;
}
}
template<typename T>
Eigen::Matrix<T, 3, 3> Exp(const T &v1, const T &v2, const T &v3)
{
T &&norm = sqrt(v1 * v1 + v2 * v2 + v3 * v3);
Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity();
if (norm > 0.00001)
{
T r_ang[3] = {v1 / norm, v2 / norm, v3 / norm};
Eigen::Matrix<T, 3, 3> K;
K << SKEW_SYM_MATRX(r_ang);
/// Roderigous Tranformation
return Eye3 + std::sin(norm) * K + (1.0 - std::cos(norm)) * K * K;
}
else
{
return Eye3;
}
}
/* Logrithm of a Rotation Matrix */
template<typename T>
Eigen::Matrix<T,3,1> Log(const Eigen::Matrix<T, 3, 3> &R)
{
T theta = (R.trace() > 3.0 - 1e-6) ? 0.0 : std::acos(0.5 * (R.trace() - 1));
Eigen::Matrix<T,3,1> K(R(2,1) - R(1,2), R(0,2) - R(2,0), R(1,0) - R(0,1));
return (std::abs(theta) < 0.001) ? (0.5 * K) : (0.5 * theta / std::sin(theta) * K);
}
template<typename T>
Eigen::Matrix<T, 3, 1> RotMtoEuler(const Eigen::Matrix<T, 3, 3> &rot)
{
T sy = sqrt(rot(0,0)*rot(0,0) + rot(1,0)*rot(1,0));
bool singular = sy < 1e-6;
T x, y, z;
if(!singular)
{
x = atan2(rot(2, 1), rot(2, 2));
y = atan2(-rot(2, 0), sy);
z = atan2(rot(1, 0), rot(0, 0));
}
else
{
x = atan2(-rot(1, 2), rot(1, 1));
y = atan2(-rot(2, 0), sy);
z = 0;
}
Eigen::Matrix<T, 3, 1> ang(x, y, z);
return ang;
}
#endif
+126
View File
@@ -0,0 +1,126 @@
#ifndef USE_IKFOM_H
#define USE_IKFOM_H
#include <IKFoM_toolkit/esekfom/esekfom.hpp>
typedef MTK::vect<3, double> vect3;
typedef MTK::SO3<double> SO3;
typedef MTK::S2<double, 98090, 10000, 1> S2;
typedef MTK::vect<1, double> vect1;
typedef MTK::vect<2, double> vect2;
MTK_BUILD_MANIFOLD(state_ikfom,
((vect3, pos))
((SO3, rot))
((SO3, offset_R_L_I))
((vect3, offset_T_L_I))
((vect3, vel))
((vect3, bg))
((vect3, ba))
((S2, grav))
);
MTK_BUILD_MANIFOLD(input_ikfom,
((vect3, acc))
((vect3, gyro))
);
MTK_BUILD_MANIFOLD(process_noise_ikfom,
((vect3, ng))
((vect3, na))
((vect3, nbg))
((vect3, nba))
);
MTK::get_cov<process_noise_ikfom>::type process_noise_cov()
{
MTK::get_cov<process_noise_ikfom>::type cov = MTK::get_cov<process_noise_ikfom>::type::Zero();
MTK::setDiagonal<process_noise_ikfom, vect3, 0>(cov, &process_noise_ikfom::ng, 0.0001);// 0.03
MTK::setDiagonal<process_noise_ikfom, vect3, 3>(cov, &process_noise_ikfom::na, 0.0001); // *dt 0.01 0.01 * dt * dt 0.05
MTK::setDiagonal<process_noise_ikfom, vect3, 6>(cov, &process_noise_ikfom::nbg, 0.00001); // *dt 0.00001 0.00001 * dt *dt 0.3 //0.001 0.0001 0.01
MTK::setDiagonal<process_noise_ikfom, vect3, 9>(cov, &process_noise_ikfom::nba, 0.00001); //0.001 0.05 0.0001/out 0.01
return cov;
}
//double L_offset_to_I[3] = {0.04165, 0.02326, -0.0284}; // Avia
//vect3 Lidar_offset_to_IMU(L_offset_to_I, 3);
Eigen::Matrix<double, 24, 1> get_f(state_ikfom &s, const input_ikfom &in)
{
Eigen::Matrix<double, 24, 1> res = Eigen::Matrix<double, 24, 1>::Zero();
vect3 omega;
in.gyro.boxminus(omega, s.bg);
vect3 a_inertial = s.rot * (in.acc-s.ba);
for(int i = 0; i < 3; i++ ){
res(i) = s.vel[i];
res(i + 3) = omega[i];
res(i + 12) = a_inertial[i] + s.grav[i];
}
return res;
}
Eigen::Matrix<double, 24, 23> df_dx(state_ikfom &s, const input_ikfom &in)
{
Eigen::Matrix<double, 24, 23> cov = Eigen::Matrix<double, 24, 23>::Zero();
cov.template block<3, 3>(0, 12) = Eigen::Matrix3d::Identity();
vect3 acc_;
in.acc.boxminus(acc_, s.ba);
vect3 omega;
in.gyro.boxminus(omega, s.bg);
cov.template block<3, 3>(12, 3) = -s.rot.toRotationMatrix()*MTK::hat(acc_);
cov.template block<3, 3>(12, 18) = -s.rot.toRotationMatrix();
Eigen::Matrix<state_ikfom::scalar, 2, 1> vec = Eigen::Matrix<state_ikfom::scalar, 2, 1>::Zero();
Eigen::Matrix<state_ikfom::scalar, 3, 2> grav_matrix;
s.S2_Mx(grav_matrix, vec, 21);
cov.template block<3, 2>(12, 21) = grav_matrix;
cov.template block<3, 3>(3, 15) = -Eigen::Matrix3d::Identity();
return cov;
}
Eigen::Matrix<double, 24, 12> df_dw(state_ikfom &s, const input_ikfom &in)
{
Eigen::Matrix<double, 24, 12> cov = Eigen::Matrix<double, 24, 12>::Zero();
cov.template block<3, 3>(12, 3) = -s.rot.toRotationMatrix();
cov.template block<3, 3>(3, 0) = -Eigen::Matrix3d::Identity();
cov.template block<3, 3>(15, 6) = Eigen::Matrix3d::Identity();
cov.template block<3, 3>(18, 9) = Eigen::Matrix3d::Identity();
return cov;
}
vect3 SO3ToEuler(const SO3 &orient)
{
Eigen::Matrix<double, 3, 1> _ang;
Eigen::Vector4d q_data = orient.coeffs().transpose();
//scalar w=orient.coeffs[3], x=orient.coeffs[0], y=orient.coeffs[1], z=orient.coeffs[2];
double sqw = q_data[3]*q_data[3];
double sqx = q_data[0]*q_data[0];
double sqy = q_data[1]*q_data[1];
double sqz = q_data[2]*q_data[2];
double unit = sqx + sqy + sqz + sqw; // if normalized is one, otherwise is correction factor
double test = q_data[3]*q_data[1] - q_data[2]*q_data[0];
if (test > 0.49999*unit) { // singularity at north pole
_ang << 2 * std::atan2(q_data[0], q_data[3]), M_PI/2, 0;
double temp[3] = {_ang[0] * 57.3, _ang[1] * 57.3, _ang[2] * 57.3};
vect3 euler_ang(temp, 3);
return euler_ang;
}
if (test < -0.49999*unit) { // singularity at south pole
_ang << -2 * std::atan2(q_data[0], q_data[3]), -M_PI/2, 0;
double temp[3] = {_ang[0] * 57.3, _ang[1] * 57.3, _ang[2] * 57.3};
vect3 euler_ang(temp, 3);
return euler_ang;
}
_ang <<
std::atan2(2*q_data[0]*q_data[3]+2*q_data[1]*q_data[2] , -sqx - sqy + sqz + sqw),
std::asin (2*test/unit),
std::atan2(2*q_data[2]*q_data[3]+2*q_data[1]*q_data[0] , sqx - sqy - sqz + sqw);
double temp[3] = {_ang[0] * 57.3, _ang[1] * 57.3, _ang[2] * 57.3};
vect3 euler_ang(temp, 3);
// euler_ang[0] = roll, euler_ang[1] = pitch, euler_ang[2] = yaw
return euler_ang;
}
#endif
+22
View File
@@ -0,0 +1,22 @@
<launch>
<arg name="rviz" default="true" />
<node pkg="fast_lio" type="fastlio_mapping" name="laserMapping" output="screen" required="true" launch-prefix="gdb -ex run --args">
<param name="imu_topic" type="string" value="/livox/imu" />
<param name="map_file_path" type="string" value=" " />
<param name="max_iteration" type="int" value="4" />
<param name="dense_map_enable" type="bool" value="1" />
<param name="fov_degree" type="double" value="75" />
<param name="filter_size_corner" type="double" value="0.2" />
<param name="filter_size_surf" type="double" value="0.2" />
<param name="filter_size_map" type="double" value="0.5" />
<param name="runtime_pos_log_enable" type="bool" value="1" />
<param name="cube_side_length" type="double" value="2000" />
</node>
<!-- <group if="$(arg rviz)">
<node launch-prefix="nice" pkg="rviz" type="rviz" name="rviz" args="-d $(find fast_lio)/rviz_cfg/loam_livox.rviz" />
</group> -->
</launch>
+70
View File
@@ -0,0 +1,70 @@
import os.path
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch.conditions import IfCondition
from launch_ros.actions import Node
def generate_launch_description():
package_path = get_package_share_directory('fast_lio')
default_config_path = os.path.join(package_path, 'config')
default_rviz_config_path = os.path.join(
package_path, 'rviz', 'fastlio.rviz')
use_sim_time = LaunchConfiguration('use_sim_time')
config_path = LaunchConfiguration('config_path')
config_file = LaunchConfiguration('config_file')
rviz_use = LaunchConfiguration('rviz')
rviz_cfg = LaunchConfiguration('rviz_cfg')
declare_use_sim_time_cmd = DeclareLaunchArgument(
'use_sim_time', default_value='false',
description='Use simulation (Gazebo) clock if true'
)
declare_config_path_cmd = DeclareLaunchArgument(
'config_path', default_value=default_config_path,
description='Yaml config file path'
)
decalre_config_file_cmd = DeclareLaunchArgument(
'config_file', default_value='mid360.yaml',
description='Config file'
)
declare_rviz_cmd = DeclareLaunchArgument(
'rviz', default_value='true',
description='Use RViz to monitor results'
)
declare_rviz_config_path_cmd = DeclareLaunchArgument(
'rviz_cfg', default_value=default_rviz_config_path,
description='RViz config file path'
)
fast_lio_node = Node(
package='fast_lio',
executable='fastlio_mapping',
parameters=[PathJoinSubstitution([config_path, config_file]),
{'use_sim_time': use_sim_time}],
output='screen'
)
rviz_node = Node(
package='rviz2',
executable='rviz2',
arguments=['-d', rviz_cfg],
condition=IfCondition(rviz_use)
)
ld = LaunchDescription()
ld.add_action(declare_use_sim_time_cmd)
ld.add_action(declare_config_path_cmd)
ld.add_action(decalre_config_file_cmd)
ld.add_action(declare_rviz_cmd)
ld.add_action(declare_rviz_config_path_cmd)
ld.add_action(fast_lio_node)
ld.add_action(rviz_node)
return ld
+70
View File
@@ -0,0 +1,70 @@
import os.path
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch.conditions import IfCondition
from launch_ros.actions import Node
def generate_launch_description():
package_path = get_package_share_directory('fast_lio')
default_config_path = os.path.join(package_path, 'config')
default_rviz_config_path = os.path.join(
package_path, 'rviz', 'fastlio.rviz')
use_sim_time = LaunchConfiguration('use_sim_time')
config_path = LaunchConfiguration('config_path')
config_file = LaunchConfiguration('config_file')
rviz_use = LaunchConfiguration('rviz')
rviz_cfg = LaunchConfiguration('rviz_cfg')
declare_use_sim_time_cmd = DeclareLaunchArgument(
'use_sim_time', default_value='false',
description='Use simulation (Gazebo) clock if true'
)
declare_config_path_cmd = DeclareLaunchArgument(
'config_path', default_value=default_config_path,
description='Yaml config file path'
)
decalre_config_file_cmd = DeclareLaunchArgument(
'config_file', default_value='unilidar_l2.yaml',
description='Config file'
)
declare_rviz_cmd = DeclareLaunchArgument(
'rviz', default_value='true',
description='Use RViz to monitor results'
)
declare_rviz_config_path_cmd = DeclareLaunchArgument(
'rviz_cfg', default_value=default_rviz_config_path,
description='RViz config file path'
)
fast_lio_node = Node(
package='fast_lio',
executable='fastlio_mapping',
parameters=[PathJoinSubstitution([config_path, config_file]),
{'use_sim_time': use_sim_time}],
output='screen'
)
rviz_node = Node(
package='rviz2',
executable='rviz2',
arguments=['-d', rviz_cfg],
condition=IfCondition(rviz_use)
)
ld = LaunchDescription()
ld.add_action(declare_use_sim_time_cmd)
ld.add_action(declare_config_path_cmd)
ld.add_action(decalre_config_file_cmd)
ld.add_action(declare_rviz_cmd)
ld.add_action(declare_rviz_config_path_cmd)
ld.add_action(fast_lio_node)
ld.add_action(rviz_node)
return ld
+7
View File
@@ -0,0 +1,7 @@
# the preintegrated Lidar states at the time of IMU measurements in a frame
float64 offset_time # the offset time of IMU measurement w.r.t the first lidar point
float64[3] acc # the preintegrated total acceleration (global frame) at the Lidar origin
float64[3] gyr # the unbiased angular velocity (body frame) at the Lidar origin
float64[3] vel # the preintegrated velocity (global frame) at the Lidar origin
float64[3] pos # the preintegrated position (global frame) at the Lidar origin
float64[9] rot # the preintegrated rotation (global frame) at the Lidar origin
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0"?>
<package format="3">
<name>fast_lio</name>
<version>0.0.0</version>
<description>
This is a modified version of LOAM which is original algorithm
is described in the following paper:
J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time.
Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014.
</description>
<maintainer email="dev@livoxtech.com">claydergc</maintainer>
<license>BSD</license>
<author email="zhangji@cmu.edu">Ji Zhang</author>
<buildtool_depend>ament_cmake</buildtool_depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<depend>geometry_msgs</depend>
<depend>nav_msgs</depend>
<depend>rclcpp</depend>
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>common_interfaces</depend>
<depend>tf2</depend>
<depend>pcl_ros</depend>
<depend>pcl_conversions</depend>
<depend>livox_ros_driver2</depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+304
View File
@@ -0,0 +1,304 @@
Panels:
- Class: rviz_common/Displays
Help Height: 78
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /Status1
Splitter Ratio: 0.5
Tree Height: 549
- Class: rviz_common/Selection
Name: Selection
- Class: rviz_common/Tool Properties
Expanded:
- /2D Goal Pose1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz_common/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
- Class: rviz_common/Time
Experimental: false
Name: Time
SyncMode: 0
SyncSource: CloudRegistered
Visualization Manager:
Class: ""
Displays:
- Class: rviz_default_plugins/TF
Enabled: true
Frame Timeout: 15
Frames:
All Enabled: true
body:
Value: true
camera_init:
Value: true
Marker Scale: 1
Name: TF
Show Arrows: true
Show Axes: true
Show Names: false
Tree:
camera_init:
body:
{}
Update Interval: 0
Value: true
- Angle Tolerance: 0.10000000149011612
Class: rviz_default_plugins/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: true
Enabled: true
Keep: 100
Name: Odometry
Position Tolerance: 0.10000000149011612
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.10000000149011612
Color: 255; 25; 0
Head Length: 0.30000001192092896
Head Radius: 0.10000000149011612
Shaft Length: 1
Shaft Radius: 0.05000000074505806
Value: Arrow
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /Odometry
Value: true
- Alpha: 1
Buffer Length: 1
Class: rviz_default_plugins/Path
Color: 25; 255; 0
Enabled: true
Head Diameter: 0.30000001192092896
Head Length: 0.20000000298023224
Length: 0.30000001192092896
Line Style: Lines
Line Width: 0.029999999329447746
Name: Path
Offset:
X: 0
Y: 0
Z: 0
Pose Color: 255; 85; 255
Pose Style: None
Radius: 0.029999999329447746
Shaft Diameter: 0.10000000149011612
Shaft Length: 0.10000000149011612
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /path
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 11.062739372253418
Min Value: -13.864188194274902
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: AxisColor
Decay Time: 30
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 186
Min Color: 0; 0; 0
Min Intensity: 0
Name: CloudRegistered
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.05000000074505806
Style: Flat Squares
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /cloud_registered
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 184
Min Color: 0; 0; 0
Min Intensity: 0
Name: CloudEffected
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.10000000149011612
Style: Flat Squares
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /cloud_effected
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: -9999
Min Value: 9999
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: AxisColor
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 255
Min Color: 0; 0; 0
Min Intensity: 0
Name: CloudMap
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.05000000074505806
Style: Flat Squares
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /Laser_map
Use Fixed Frame: true
Use rainbow: true
Value: true
Enabled: true
Global Options:
Background Color: 0; 0; 0
Fixed Frame: camera_init
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
Hide Inactive Objects: true
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Line color: 128; 128; 0
- Class: rviz_default_plugins/SetInitialPose
Covariance x: 0.25
Covariance y: 0.25
Covariance yaw: 0.06853891909122467
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /initialpose
- Class: rviz_default_plugins/SetGoal
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /goal_pose
- Class: rviz_default_plugins/PublishPoint
Single click: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /clicked_point
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 216.99887084960938
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Focal Point:
X: -0.008504047989845276
Y: -0.0005770106799900532
Z: 0.034441977739334106
Focal Shape Fixed Size: true
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 1.5697963237762451
Target Frame: <Fixed Frame>
Value: Orbit (rviz_default_plugins)
Yaw: 4.88355827331543
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 846
Hide Left Dock: false
Hide Right Dock: false
QMainWindow State: 000000ff00000000fd000000040000000000000156000002b0fc0200000008fb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d000002b0000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261000000010000010f000002b0fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073000000003d000002b0000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000005ad0000003efc0100000002fb0000000800540069006d00650100000000000005ad000002fb00fffffffb0000000800540069006d0065010000000000000450000000000000000000000451000002b000000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Time:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: false
Width: 1453
X: 368
Y: 104
View File
+358
View File
@@ -0,0 +1,358 @@
Panels:
- Class: rviz/Displays
Help Height: 0
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /mapping1
- /mapping1/surround1
- /mapping1/currPoints1
- /mapping1/currPoints1/Autocompute Value Bounds1
- /Odometry1/Odometry1
- /Odometry1/Odometry1/Shape1
- /Odometry1/Odometry1/Covariance1
- /Odometry1/Odometry1/Covariance1/Position1
- /Odometry1/Odometry1/Covariance1/Orientation1
- /MarkerArray1/Namespaces1
Splitter Ratio: 0.6432291865348816
Tree Height: 811
- Class: rviz/Selection
Name: Selection
- Class: rviz/Tool Properties
Expanded:
- /2D Pose Estimate1
- /2D Nav Goal1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
- Class: rviz/Time
Experimental: false
Name: Time
SyncMode: 0
SyncSource: surround
Preferences:
PromptSaveOnExit: true
Toolbars:
toolButtonStyle: 2
Visualization Manager:
Class: ""
Displays:
- Alpha: 1
Cell Size: 1000
Class: rviz/Grid
Color: 160; 160; 164
Enabled: false
Line Style:
Line Width: 0.029999999329447746
Value: Lines
Name: Grid
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 40
Reference Frame: <Fixed Frame>
Value: false
- Class: rviz/Axes
Enabled: false
Length: 0.699999988079071
Name: Axes
Radius: 0.05999999865889549
Reference Frame: <Fixed Frame>
Value: false
- Class: rviz/Group
Displays:
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 238; 238; 236
Color Transformer: Intensity
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 238; 238; 236
Name: surround
Position Transformer: XYZ
Queue Size: 1
Selectable: false
Size (Pixels): 3
Size (m): 0.05000000074505806
Style: Points
Topic: /cloud_registered
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 0.10000000149011612
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 15
Min Value: -5
Value: false
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 1000
Enabled: true
Invert Rainbow: true
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: currPoints
Position Transformer: XYZ
Queue Size: 100000
Selectable: true
Size (Pixels): 1
Size (m): 0.009999999776482582
Style: Points
Topic: /cloud_registered
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 0; 0
Color Transformer: FlatColor
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: PointCloud2
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.10000000149011612
Style: Flat Squares
Topic: /Laser_map
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
Enabled: true
Name: mapping
- Class: rviz/Group
Displays:
- Angle Tolerance: 0.009999999776482582
Class: rviz/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: true
Enabled: true
Keep: 1
Name: Odometry
Position Tolerance: 0.0010000000474974513
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.20000000298023224
Color: 255; 85; 0
Head Length: 0
Head Radius: 0
Shaft Length: 0.05000000074505806
Shaft Radius: 0.05000000074505806
Value: Axes
Topic: /Odometry
Unreliable: false
Value: true
Enabled: true
Name: Odometry
- Class: rviz/Axes
Enabled: true
Length: 0.699999988079071
Name: Axes
Radius: 0.10000000149011612
Reference Frame: <Fixed Frame>
Value: true
- Alpha: 0
Buffer Length: 2
Class: rviz/Path
Color: 25; 255; 255
Enabled: true
Head Diameter: 0
Head Length: 0
Length: 0.30000001192092896
Line Style: Billboards
Line Width: 0.20000000298023224
Name: Path
Offset:
X: 0
Y: 0
Z: 0
Pose Color: 25; 255; 255
Pose Style: None
Radius: 0.029999999329447746
Shaft Diameter: 0.4000000059604645
Shaft Length: 0.4000000059604645
Topic: /path
Unreliable: false
Value: true
- Alpha: 1
Autocompute Intensity Bounds: false
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 239; 41; 41
Max Intensity: 0
Min Color: 239; 41; 41
Min Intensity: 0
Name: PointCloud2
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 4
Size (m): 0.30000001192092896
Style: Spheres
Topic: /cloud_effected
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 13.139549255371094
Min Value: -32.08251953125
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 138; 226; 52
Color Transformer: FlatColor
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 138; 226; 52
Min Color: 138; 226; 52
Name: PointCloud2
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.10000000149011612
Style: Flat Squares
Topic: /Laser_map
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
- Class: rviz/MarkerArray
Enabled: false
Marker Topic: /MarkerArray
Name: MarkerArray
Namespaces:
{}
Queue Size: 100
Value: false
Enabled: true
Global Options:
Background Color: 0; 0; 0
Default Light: true
Fixed Frame: camera_init
Frame Rate: 10
Name: root
Tools:
- Class: rviz/Interact
Hide Inactive Objects: true
- Class: rviz/MoveCamera
- Class: rviz/Select
- Class: rviz/FocusCamera
- Class: rviz/Measure
- Class: rviz/SetInitialPose
Theta std deviation: 0.2617993950843811
Topic: /initialpose
X std deviation: 0.5
Y std deviation: 0.5
- Class: rviz/SetGoal
Topic: /move_base_simple/goal
- Class: rviz/PublishPoint
Single click: true
Topic: /clicked_point
Value: true
Views:
Current:
Class: rviz/Orbit
Distance: 46.0853271484375
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Focal Point:
X: -4.982542037963867
Y: -15.83572006225586
Z: -3.063523054122925
Focal Shape Fixed Size: true
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 0.399796724319458
Target Frame: global
Value: Orbit (rviz)
Yaw: 1.277182698249817
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 1028
Hide Left Dock: false
Hide Right Dock: true
QMainWindow State: 000000ff00000000fd0000000400000000000001c800000368fc020000000dfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000002700000368000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d0061006700650000000297000001dc0000000000000000fb0000000a0049006d0061006700650000000394000001600000000000000000fb0000000a0049006d00610067006501000002c5000000c70000000000000000fb0000000a0049006d00610067006501000002c5000000c70000000000000000fb0000000a0049006d00610067006501000002c5000000c700000000000000000000000100000152000004b7fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073000000003d000004b7000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e100000197000000030000061f00000052fc0100000002fb0000000800540069006d006501000000000000061f000002eb00fffffffb0000000800540069006d00650100000000000004500000000000000000000004510000036800000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Time:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: true
Width: 1567
X: 67
Y: 24
+379
View File
@@ -0,0 +1,379 @@
#include <cmath>
#include <math.h>
#include <deque>
#include <mutex>
#include <thread>
#include <fstream>
#include <csignal>
#include <so3_math.h>
#include <Eigen/Eigen>
#include <common_lib.h>
#include <pcl/common/io.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <condition_variable>
#include <nav_msgs/msg/odometry.hpp>
#include <pcl/common/transforms.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl_conversions/pcl_conversions.h>
#include <sensor_msgs/msg/imu.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <geometry_msgs/msg/vector3.hpp>
#include "use-ikfom.hpp"
/// *************Preconfiguration
#define MAX_INI_COUNT (10)
const bool time_list(PointType &x, PointType &y) {return (x.curvature < y.curvature);};
/// *************IMU Process and undistortion
class ImuProcess
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
ImuProcess();
~ImuProcess();
void Reset();
// void Reset(double start_timestamp, const sensor_msgs::ImuConstPtr &lastimu);
void Reset(double start_timestamp, const sensor_msgs::msg::Imu::ConstSharedPtr &lastimu);
void set_extrinsic(const V3D &transl, const M3D &rot);
void set_extrinsic(const V3D &transl);
void set_extrinsic(const MD(4,4) &T);
void set_gyr_cov(const V3D &scaler);
void set_acc_cov(const V3D &scaler);
void set_gyr_bias_cov(const V3D &b_g);
void set_acc_bias_cov(const V3D &b_a);
Eigen::Matrix<double, 12, 12> Q;
void Process(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI::Ptr pcl_un_);
ofstream fout_imu;
V3D cov_acc;
V3D cov_gyr;
V3D cov_acc_scale;
V3D cov_gyr_scale;
V3D cov_bias_gyr;
V3D cov_bias_acc;
double first_lidar_time;
private:
void IMU_init(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, int &N);
void UndistortPcl(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI &pcl_in_out);
PointCloudXYZI::Ptr cur_pcl_un_;
// sensor_msgs::ImuConstPtr last_imu_;
sensor_msgs::msg::Imu::ConstSharedPtr last_imu_;
deque<sensor_msgs::msg::Imu::ConstSharedPtr> v_imu_;
vector<Pose6D> IMUpose;
vector<M3D> v_rot_pcl_;
M3D Lidar_R_wrt_IMU;
V3D Lidar_T_wrt_IMU;
V3D mean_acc;
V3D mean_gyr;
V3D angvel_last;
V3D acc_s_last;
double start_timestamp_;
double last_lidar_end_time_;
int init_iter_num = 1;
bool b_first_frame_ = true;
bool imu_need_init_ = true;
};
ImuProcess::ImuProcess()
: b_first_frame_(true), imu_need_init_(true), start_timestamp_(-1)
{
init_iter_num = 1;
Q = process_noise_cov();
cov_acc = V3D(0.1, 0.1, 0.1);
cov_gyr = V3D(0.1, 0.1, 0.1);
cov_bias_gyr = V3D(0.0001, 0.0001, 0.0001);
cov_bias_acc = V3D(0.0001, 0.0001, 0.0001);
mean_acc = V3D(0, 0, -1.0);
mean_gyr = V3D(0, 0, 0);
angvel_last = Zero3d;
Lidar_T_wrt_IMU = Zero3d;
Lidar_R_wrt_IMU = Eye3d;
last_imu_.reset(new sensor_msgs::msg::Imu());
}
ImuProcess::~ImuProcess() {}
void ImuProcess::Reset()
{
// ROS_WARN("Reset ImuProcess");
mean_acc = V3D(0, 0, -1.0);
mean_gyr = V3D(0, 0, 0);
angvel_last = Zero3d;
imu_need_init_ = true;
start_timestamp_ = -1;
init_iter_num = 1;
v_imu_.clear();
IMUpose.clear();
last_imu_.reset(new sensor_msgs::msg::Imu());
cur_pcl_un_.reset(new PointCloudXYZI());
}
void ImuProcess::set_extrinsic(const MD(4,4) &T)
{
Lidar_T_wrt_IMU = T.block<3,1>(0,3);
Lidar_R_wrt_IMU = T.block<3,3>(0,0);
}
void ImuProcess::set_extrinsic(const V3D &transl)
{
Lidar_T_wrt_IMU = transl;
Lidar_R_wrt_IMU.setIdentity();
}
void ImuProcess::set_extrinsic(const V3D &transl, const M3D &rot)
{
Lidar_T_wrt_IMU = transl;
Lidar_R_wrt_IMU = rot;
}
void ImuProcess::set_gyr_cov(const V3D &scaler)
{
cov_gyr_scale = scaler;
}
void ImuProcess::set_acc_cov(const V3D &scaler)
{
cov_acc_scale = scaler;
}
void ImuProcess::set_gyr_bias_cov(const V3D &b_g)
{
cov_bias_gyr = b_g;
}
void ImuProcess::set_acc_bias_cov(const V3D &b_a)
{
cov_bias_acc = b_a;
}
void ImuProcess::IMU_init(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, int &N)
{
/** 1. initializing the gravity, gyro bias, acc and gyro covariance
** 2. normalize the acceleration measurenments to unit gravity **/
V3D cur_acc, cur_gyr;
if (b_first_frame_)
{
Reset();
N = 1;
b_first_frame_ = false;
const auto &imu_acc = meas.imu.front()->linear_acceleration;
const auto &gyr_acc = meas.imu.front()->angular_velocity;
mean_acc << imu_acc.x, imu_acc.y, imu_acc.z;
mean_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z;
first_lidar_time = meas.lidar_beg_time;
}
for (const auto &imu : meas.imu)
{
const auto &imu_acc = imu->linear_acceleration;
const auto &gyr_acc = imu->angular_velocity;
cur_acc << imu_acc.x, imu_acc.y, imu_acc.z;
cur_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z;
mean_acc += (cur_acc - mean_acc) / N;
mean_gyr += (cur_gyr - mean_gyr) / N;
cov_acc = cov_acc * (N - 1.0) / N + (cur_acc - mean_acc).cwiseProduct(cur_acc - mean_acc) * (N - 1.0) / (N * N);
cov_gyr = cov_gyr * (N - 1.0) / N + (cur_gyr - mean_gyr).cwiseProduct(cur_gyr - mean_gyr) * (N - 1.0) / (N * N);
// cout<<"acc norm: "<<cur_acc.norm()<<" "<<mean_acc.norm()<<endl;
N ++;
}
state_ikfom init_state = kf_state.get_x();
init_state.grav = S2(- mean_acc / mean_acc.norm() * G_m_s2);
//state_inout.rot = Eye3d; // Exp(mean_acc.cross(V3D(0, 0, -1 / scale_gravity)));
init_state.bg = mean_gyr;
init_state.offset_T_L_I = Lidar_T_wrt_IMU;
init_state.offset_R_L_I = Lidar_R_wrt_IMU;
kf_state.change_x(init_state);
esekfom::esekf<state_ikfom, 12, input_ikfom>::cov init_P = kf_state.get_P();
init_P.setIdentity();
init_P(6,6) = init_P(7,7) = init_P(8,8) = 0.00001;
init_P(9,9) = init_P(10,10) = init_P(11,11) = 0.00001;
init_P(15,15) = init_P(16,16) = init_P(17,17) = 0.0001;
init_P(18,18) = init_P(19,19) = init_P(20,20) = 0.001;
init_P(21,21) = init_P(22,22) = 0.00001;
kf_state.change_P(init_P);
last_imu_ = meas.imu.back();
}
void ImuProcess::UndistortPcl(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI &pcl_out)
{
/*** add the imu of the last frame-tail to the of current frame-head ***/
auto v_imu = meas.imu;
v_imu.push_front(last_imu_);
const double &imu_beg_time = rclcpp::Time(v_imu.front()->header.stamp).seconds();
const double &imu_end_time = rclcpp::Time(v_imu.back()->header.stamp).seconds();
const double &pcl_beg_time = meas.lidar_beg_time;
const double &pcl_end_time = meas.lidar_end_time;
/*** sort point clouds by offset time ***/
pcl_out = *(meas.lidar);
sort(pcl_out.points.begin(), pcl_out.points.end(), time_list);
// cout<<"[ IMU Process ]: Process lidar from "<<pcl_beg_time<<" to "<<pcl_end_time<<", " \
// <<meas.imu.size()<<" imu msgs from "<<imu_beg_time<<" to "<<imu_end_time<<endl;
/*** Initialize IMU pose ***/
state_ikfom imu_state = kf_state.get_x();
IMUpose.clear();
IMUpose.push_back(set_pose6d(0.0, acc_s_last, angvel_last, imu_state.vel, imu_state.pos, imu_state.rot.toRotationMatrix()));
/*** forward propagation at each imu point ***/
V3D angvel_avr, acc_avr, acc_imu, vel_imu, pos_imu;
M3D R_imu;
double dt = 0;
input_ikfom in;
for (auto it_imu = v_imu.begin(); it_imu < (v_imu.end() - 1); it_imu++)
{
auto &&head = *(it_imu);
auto &&tail = *(it_imu + 1);
double tail_stamp = rclcpp::Time(tail->header.stamp).seconds();
double head_stamp = rclcpp::Time(head->header.stamp).seconds();
if (tail_stamp < last_lidar_end_time_) continue;
angvel_avr<<0.5 * (head->angular_velocity.x + tail->angular_velocity.x),
0.5 * (head->angular_velocity.y + tail->angular_velocity.y),
0.5 * (head->angular_velocity.z + tail->angular_velocity.z);
acc_avr <<0.5 * (head->linear_acceleration.x + tail->linear_acceleration.x),
0.5 * (head->linear_acceleration.y + tail->linear_acceleration.y),
0.5 * (head->linear_acceleration.z + tail->linear_acceleration.z);
// fout_imu << setw(10) << head->header.stamp.toSec() - first_lidar_time << " " << angvel_avr.transpose() << " " << acc_avr.transpose() << endl;
acc_avr = acc_avr * G_m_s2 / mean_acc.norm(); // - state_inout.ba;
if(head_stamp < last_lidar_end_time_)
{
dt = tail_stamp - last_lidar_end_time_;
// dt = tail->header.stamp.toSec() - pcl_beg_time;
}
else
{
dt = tail_stamp - head_stamp;
}
in.acc = acc_avr;
in.gyro = angvel_avr;
Q.block<3, 3>(0, 0).diagonal() = cov_gyr;
Q.block<3, 3>(3, 3).diagonal() = cov_acc;
Q.block<3, 3>(6, 6).diagonal() = cov_bias_gyr;
Q.block<3, 3>(9, 9).diagonal() = cov_bias_acc;
kf_state.predict(dt, Q, in);
/* save the poses at each IMU measurements */
imu_state = kf_state.get_x();
angvel_last = angvel_avr - imu_state.bg;
acc_s_last = imu_state.rot * (acc_avr - imu_state.ba);
for(int i=0; i<3; i++)
{
acc_s_last[i] += imu_state.grav[i];
}
double &&offs_t = tail_stamp - pcl_beg_time;
IMUpose.push_back(set_pose6d(offs_t, acc_s_last, angvel_last, imu_state.vel, imu_state.pos, imu_state.rot.toRotationMatrix()));
}
/*** calculated the pos and attitude prediction at the frame-end ***/
double note = pcl_end_time > imu_end_time ? 1.0 : -1.0;
dt = note * (pcl_end_time - imu_end_time);
kf_state.predict(dt, Q, in);
imu_state = kf_state.get_x();
last_imu_ = meas.imu.back();
last_lidar_end_time_ = pcl_end_time;
/*** undistort each lidar point (backward propagation) ***/
if (pcl_out.points.begin() == pcl_out.points.end()) return;
auto it_pcl = pcl_out.points.end() - 1;
for (auto it_kp = IMUpose.end() - 1; it_kp != IMUpose.begin(); it_kp--)
{
auto head = it_kp - 1;
auto tail = it_kp;
R_imu<<MAT_FROM_ARRAY(head->rot);
// cout<<"head imu acc: "<<acc_imu.transpose()<<endl;
vel_imu<<VEC_FROM_ARRAY(head->vel);
pos_imu<<VEC_FROM_ARRAY(head->pos);
acc_imu<<VEC_FROM_ARRAY(tail->acc);
angvel_avr<<VEC_FROM_ARRAY(tail->gyr);
for(; it_pcl->curvature / double(1000) > head->offset_time; it_pcl --)
{
dt = it_pcl->curvature / double(1000) - head->offset_time;
/* Transform to the 'end' frame, using only the rotation
* Note: Compensation direction is INVERSE of Frame's moving direction
* So if we want to compensate a point at timestamp-i to the frame-e
* P_compensate = R_imu_e ^ T * (R_i * P_i + T_ei) where T_ei is represented in global frame */
M3D R_i(R_imu * Exp(angvel_avr, dt));
V3D P_i(it_pcl->x, it_pcl->y, it_pcl->z);
V3D T_ei(pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt - imu_state.pos);
V3D P_compensate = imu_state.offset_R_L_I.conjugate() * (imu_state.rot.conjugate() * (R_i * (imu_state.offset_R_L_I * P_i + imu_state.offset_T_L_I) + T_ei) - imu_state.offset_T_L_I);// not accurate!
// save Undistorted points and their rotation
it_pcl->x = P_compensate(0);
it_pcl->y = P_compensate(1);
it_pcl->z = P_compensate(2);
if (it_pcl == pcl_out.points.begin()) break;
}
}
}
void ImuProcess::Process(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI::Ptr cur_pcl_un_)
{
double t1,t2,t3;
t1 = omp_get_wtime();
if(meas.imu.empty()) {return;};
assert(meas.lidar != nullptr);
if (imu_need_init_)
{
/// The very first lidar frame
IMU_init(meas, kf_state, init_iter_num);
imu_need_init_ = true;
last_imu_ = meas.imu.back();
state_ikfom imu_state = kf_state.get_x();
if (init_iter_num > MAX_INI_COUNT)
{
cov_acc *= pow(G_m_s2 / mean_acc.norm(), 2);
imu_need_init_ = false;
cov_acc = cov_acc_scale;
cov_gyr = cov_gyr_scale;
std::cout << "IMU Initial Done" << std::endl;
// ROS_INFO("IMU Initial Done: Gravity: %.4f %.4f %.4f %.4f; state.bias_g: %.4f %.4f %.4f; acc covarience: %.8f %.8f %.8f; gry covarience: %.8f %.8f %.8f",\
// imu_state.grav[0], imu_state.grav[1], imu_state.grav[2], mean_acc.norm(), cov_bias_gyr[0], cov_bias_gyr[1], cov_bias_gyr[2], cov_acc[0], cov_acc[1], cov_acc[2], cov_gyr[0], cov_gyr[1], cov_gyr[2]);
fout_imu.open(DEBUG_FILE_DIR("imu.txt"),ios::out);
}
return;
}
UndistortPcl(meas, kf_state, *cur_pcl_un_);
t2 = omp_get_wtime();
t3 = omp_get_wtime();
// cout<<"[ IMU Process ]: Time: "<<t3 - t1<<endl;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+196
View File
@@ -0,0 +1,196 @@
// #include <ros/ros.h>
#include <rclcpp/rclcpp.hpp>
#include <pcl_conversions/pcl_conversions.h>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <livox_ros_driver2/msg/custom_msg.hpp>
using namespace std;
#define IS_VALID(a) ((abs(a) > 1e8) ? true : false)
typedef pcl::PointXYZINormal PointType;
typedef pcl::PointCloud<PointType> PointCloudXYZI;
enum LID_TYPE
{
AVIA = 1,
VELO16,
OUST64,
MID360
}; //{1, 2, 3}
enum TIME_UNIT
{
SEC = 0,
MS = 1,
US = 2,
NS = 3
};
enum Feature
{
Nor,
Poss_Plane,
Real_Plane,
Edge_Jump,
Edge_Plane,
Wire,
ZeroPoint
};
enum Surround
{
Prev,
Next
};
enum E_jump
{
Nr_nor,
Nr_zero,
Nr_180,
Nr_inf,
Nr_blind
};
struct orgtype
{
double range;
double dista;
double angle[2];
double intersect;
E_jump edj[2];
Feature ftype;
orgtype()
{
range = 0;
edj[Prev] = Nr_nor;
edj[Next] = Nr_nor;
ftype = Nor;
intersect = 2;
}
};
namespace velodyne_ros
{
struct EIGEN_ALIGN16 Point
{
PCL_ADD_POINT4D;
float intensity;
float time;
uint16_t ring;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
} // namespace velodyne_ros
POINT_CLOUD_REGISTER_POINT_STRUCT(velodyne_ros::Point,
(float, x, x)(float, y, y)(float, z, z)(float, intensity,
intensity)(float, time, time)(uint16_t, ring,
ring))
namespace ouster_ros
{
struct EIGEN_ALIGN16 Point
{
PCL_ADD_POINT4D;
float intensity;
uint32_t t;
uint16_t reflectivity;
uint8_t ring;
uint16_t ambient;
uint32_t range;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
} // namespace ouster_ros
// clang-format off
POINT_CLOUD_REGISTER_POINT_STRUCT(ouster_ros::Point,
(float, x, x)
(float, y, y)
(float, z, z)
(float, intensity, intensity)
// use std::uint32_t to avoid conflicting with pcl::uint32_t
(std::uint32_t, t, t)
(std::uint16_t, reflectivity, reflectivity)
(std::uint8_t, ring, ring)
(std::uint16_t, ambient, ambient)
(std::uint32_t, range, range)
)
namespace livox_ros
{
typedef struct {
float x; /**< X axis, Unit:m */
float y; /**< Y axis, Unit:m */
float z; /**< Z axis, Unit:m */
float reflectivity; /**< Reflectivity */
uint8_t tag; /**< Livox point tag */
uint8_t line; /**< Laser line id */
} LivoxPointXyzrtl;
typedef struct {
float x; /**< X axis, Unit:m */
float y; /**< Y axis, Unit:m */
float z; /**< Z axis, Unit:m */
float intensity; /**< Intensity */
uint8_t tag; /**< Livox point tag */
uint8_t line; /**< Laser line id */
} LivoxPointXyzitl;
}
POINT_CLOUD_REGISTER_POINT_STRUCT(livox_ros::LivoxPointXyzrtl,
(float, x, x)
(float, y, y)
(float, z, z)
(float, reflectivity, reflectivity)
(uint8_t, tag, tag)
(uint8_t, line, line)
)
POINT_CLOUD_REGISTER_POINT_STRUCT(livox_ros::LivoxPointXyzitl,
(float, x, x)
(float, y, y)
(float, z, z)
(float, intensity, intensity)
(uint8_t, tag, tag)
(uint8_t, line, line)
)
class Preprocess
{
public:
// EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Preprocess();
~Preprocess();
void process(const livox_ros_driver2::msg::CustomMsg::UniquePtr &msg, PointCloudXYZI::Ptr &pcl_out);
void process(const sensor_msgs::msg::PointCloud2::UniquePtr &msg, PointCloudXYZI::Ptr &pcl_out);
void set(bool feat_en, int lid_type, double bld, int pfilt_num);
// sensor_msgs::PointCloud2::ConstPtr pointcloud;
PointCloudXYZI pl_full, pl_corn, pl_surf;
PointCloudXYZI pl_buff[128]; //maximum 128 line lidar
vector<orgtype> typess[128]; //maximum 128 line lidar
float time_unit_scale;
int lidar_type, point_filter_num, N_SCANS, SCAN_RATE, time_unit;
double blind;
bool feature_enabled, given_offset_time;
// ros::Publisher pub_full, pub_surf, pub_corn;
private:
void avia_handler(const livox_ros_driver2::msg::CustomMsg::UniquePtr &msg);
void oust64_handler(const sensor_msgs::msg::PointCloud2::UniquePtr &msg);
void velodyne_handler(const sensor_msgs::msg::PointCloud2::UniquePtr &msg);
void mid360_handler(const sensor_msgs::msg::PointCloud2::UniquePtr &msg);
void default_handler(const sensor_msgs::msg::PointCloud2::UniquePtr &msg);
void give_feature(PointCloudXYZI &pl, vector<orgtype> &types);
void pub_func(PointCloudXYZI &pl, const rclcpp::Time &ct);
int plane_judge(const PointCloudXYZI &pl, vector<orgtype> &types, uint i, uint &i_nex, Eigen::Vector3d &curr_direct);
bool small_plane(const PointCloudXYZI &pl, vector<orgtype> &types, uint i_cur, uint &i_nex, Eigen::Vector3d &curr_direct);
bool edge_jump_judge(const PointCloudXYZI &pl, vector<orgtype> &types, uint i, Surround nor_dir);
int group_size;
double disA, disB, inf_bound;
double limit_maxmid, limit_midmin, limit_maxmin;
double p2l_ratio;
double jump_up_limit, jump_down_limit;
double cos160;
double edgea, edgeb;
double smallp_intersect, smallp_ratio;
double vx, vy, vz;
};
+134
View File
@@ -0,0 +1,134 @@
# AGV AutoCharge ROS2 Package
这是一个为ROS2 Humble设计的AGV自动充电系统软件包。
## 功能特性
- 监听充电桩位置更新
- 持续发布可视化标记
- 键盘交互启动导航功能
- 导航成功后启动串口控制
- 支持充电状态检测和控制
## 安装依赖
确保您的系统已安装以下依赖:
```bash
# ROS2 Humble基础包
sudo apt install ros-humble-rclpy
sudo apt install ros-humble-geometry-msgs
sudo apt install ros-humble-std-msgs
sudo apt install ros-humble-nav-msgs
sudo apt install ros-humble-visualization-msgs
sudo apt install ros-humble-nav2-simple-commander
# Python依赖
pip3 install pyserial
```
## 编译安装
```bash
# 进入ROS2工作空间
cd /path/to/your/ros2_ws/src
# 复制软件包到工作空间
cp -r agv_autocharge_ros2 .
# 编译软件包
cd ..
colcon build --packages-select agv_autocharge_ros2
# 加载环境变量
source install/setup.bash
```
## 使用方法
### 启动节点
```bash
# 启动自动充电控制器节点
ros2 run agv_autocharge_ros2 combined_auto_recharger
```
### 节点功能
- 监听 `/charger_position_update` 话题,接收充电桩位置更新
- 发布 `/goal_marker` 话题,在RViz中显示充电桩位置标记
- 发布 `/cmd_vel` 话题,控制机器人运动
- 按键 `q` 启动导航到充电桩
- 导航成功后自动启动串口控制
### 配置文件
充电桩位置配置文件位于:
```
config/charger_position.json
```
文件格式:
```json
{
"p_x": 1.329015495451769,
"p_y": 0.31961151635354823,
"orien_z": 0.4981823289472456,
"orien_w": 0.8670722963655905
}
```
### 话题接口
#### 订阅话题
- `/charger_position_update` (geometry_msgs/PoseStamped): 充电桩位置更新
#### 发布话题
- `/goal_marker` (visualization_msgs/MarkerArray): 充电桩位置可视化标记
- `/cmd_vel` (geometry_msgs/Twist): 机器人运动控制
- `/chassis_security` (std_msgs/Int8): 底盘安全控制
### 串口配置
默认串口配置:
- 端口: `/dev/ttyCH341USB0`
- 波特率: 9600
- 超时: 1秒
可以根据需要修改代码中的串口参数。
## 操作说明
1. 启动节点后,系统会自动加载充电桩位置配置
2. 系统会定期发布充电桩标记到RViz进行可视化
3. 按下键盘上的 `q` 键启动导航到充电桩
4. 导航成功后,系统会自动启动串口控制功能
5. 串口控制会根据接收到的数据控制机器人运动
6.`Ctrl+C` 退出程序
## 故障排除
### 常见问题
1. **串口无法打开**
- 检查串口设备是否连接
- 确认串口权限设置
- 验证串口设备名称
2. **导航失败**
- 确认Nav2导航系统正常运行
- 检查充电桩位置配置是否正确
- 验证地图和定位系统状态
3. **RViz中看不到标记**
- 确认RViz已订阅 `/goal_marker` 话题
- 检查MarkerArray显示设置
- 验证坐标系设置是否为'map'
## 许可证
MIT License
## 维护者
请联系维护者获取技术支持。
+10
View File
@@ -0,0 +1,10 @@
"""
AGV AutoCharge ROS2 Package
This package provides automatic charging functionality for AGV robots using ROS2 Humble.
It includes position management, visualization, navigation, and serial control features.
"""
__version__ = '1.0.0'
__author__ = 'Your Name'
__email__ = 'your-email@example.com'
@@ -0,0 +1,612 @@
#!/usr/bin/env python3
# coding=utf-8
"""
合并的自动充电控制器 - 结合位置管理、可视化和导航功能
- 监听充电桩位置更新
- 持续发布可视化标记
- 按键'q'启动导航功能
- 导航成功后启动串口控制
"""
# 引用ros库
import rclpy
from rclpy.node import Node
from nav2_simple_commander.robot_navigator import BasicNavigator, TaskResult
from rclpy.duration import Duration
# 用到的变量定义
from std_msgs.msg import Bool
from std_msgs.msg import Int8
from std_msgs.msg import UInt8
from std_msgs.msg import Float32
# 用于记录充电桩位置、发布导航点
from geometry_msgs.msg import PoseStamped, Twist
# rviz可视化相关
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
# 里程计话题相关
from nav_msgs.msg import Odometry
# 键盘控制相关
import sys
import select
import termios
import tty
# 延迟相关
import time
import threading
# 读写充电桩位置文件
import json
import math
import yaml
import os
# 导入串口解析模块
from .serial_can_parser import SerialCANParser
# 存放充电桩位置的文件位置 - 参考原始auto_recharger.py的路径设置方式
def find_config_files():
"""查找配置文件路径"""
# 首先尝试几个可能的位置
possible_paths = [
# 开发环境路径
'/home/elephant/agv_pro_ros2/src/agv_pro_autocharge/config',
# 你的工作空间路径
'/home/elephant/agv_pro_ros2/src/agv_pro_autocharge/config',
# 当前包的相对路径
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config'),
# 安装路径
'/home/elephant/agv_pro_ros2/install/agv_pro_autocharge/share/agv_pro_autocharge/config'
]
for config_dir in possible_paths:
yaml_path = os.path.join(config_dir, 'nav_goal_params.yaml')
json_path = os.path.join(config_dir, 'charger_position.json')
print(f"Checking config directory: {config_dir}")
if os.path.exists(yaml_path) and os.path.exists(json_path):
print(f"Found config files in: {config_dir}")
return yaml_path, json_path
# 如果都找不到,直接报错
print("ERROR: Could not find config files in any of the following locations:")
for path in possible_paths:
print(f" - {path}")
print("Please ensure the config files exist in one of these directories.")
# 返回第一个路径作为默认值,但文件可能不存在
return os.path.join(possible_paths[0], 'nav_goal_params.yaml'), os.path.join(possible_paths[0], 'charger_position.json')
# 获取配置文件路径
yaml_file, json_file = find_config_files()
# print_and_fixRetract相关,用于打印带颜色的信息
RESET = '\033[0m'
RED = '\033[1;31m'
GREEN = '\033[1;32m'
YELLOW= '\033[1;33m'
BLUE = '\033[1;34m'
PURPLE= '\033[1;35m'
CYAN = '\033[1;36m'
# 圆周率
PI = 3.1415926535897
if os.name == 'nt':
import msvcrt
else:
import termios
import tty
settings = None
if os.name != 'nt' and sys.stdin.isatty():
settings = list(termios.tcgetattr(sys.stdin))
def get_key(settings):
if os.name == 'nt':
return msvcrt.getch().decode('utf-8')
else:
if sys.stdin.isatty():
tty.setraw(sys.stdin.fileno())
rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
if rlist:
key = sys.stdin.read(1)
else:
key = ''
if sys.stdin.isatty() and settings:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
return key
def print_and_fixRetract(str):
global settings
'''键盘控制会导致回调函数内使用print()出现自动缩进的问题,此函数可以解决该现象'''
if sys.stdin.isatty() and settings:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
print(str)
class CombinedAutoRecharger(Node):
def __init__(self):
# 创建节点
super().__init__("combined_auto_recharger")
print_and_fixRetract('Combined Auto Recharger Node Started!')
# 导航状态标记
self.navigation_active = False
# 串口控制相关
self.parser = None
self.serial_control_active = False
self.navigation_requested = False # 添加导航请求标志
# 创建导航器
self.navigator = BasicNavigator()
# 加载充电桩位置信息
self.load_charger_position()
# 加载导航参数
self.load_nav_goal_params()
# 创建发布者
self.robot_security_off_pub = self.create_publisher(Int8, '/chassis_security', 10)
self.Charger_marker_pub = self.create_publisher(MarkerArray, '/goal_marker', 10)
self.cmd_vel_pub = self.create_publisher(Twist, '/cmd_vel', 10)
# 创建订阅者 - 只订阅充电桩位置更新
self.Charger_Position_Update_sub = self.create_subscription(
PoseStamped, "/charger_position_update",
self.Position_Update_callback, 10)
# 创建定时器,定期发布充电桩标记(每2秒发布一次)
self.marker_timer = self.create_timer(2.0, self.timer_callback)
# 创建导航检查定时器(每0.5秒检查一次导航请求)
self.navigation_timer = self.create_timer(0.5, self.check_navigation_request)
# 发布初始充电桩位置标记
self.update_charger_visualization()
print_and_fixRetract('Combined auto recharger node initialized successfully!')
print_and_fixRetract(f'{GREEN}Press "q" to start navigation, Ctrl+C to exit{RESET}')
def load_nav_goal_params(self):
"""加载导航目标参数(前方距离和角度)"""
print_and_fixRetract(f"Attempting to load nav goal params from: {yaml_file}")
print_and_fixRetract(f"File exists? {os.path.exists(yaml_file)}")
try:
with open(yaml_file, 'r', encoding='utf-8') as f:
params = yaml.safe_load(f)
print_and_fixRetract(f"Raw params from file: {params}")
self.forward_distance = float(params.get('forward_distance', 1.0))
self.yaw_offset_deg = float(params.get('yaw_offset_deg', 0.0))
print_and_fixRetract(f"Successfully loaded nav goal params: forward_distance={self.forward_distance}, yaw_offset_deg={self.yaw_offset_deg}")
except FileNotFoundError:
print_and_fixRetract(f"{RED}Nav goal params file not found: {yaml_file}{RESET}")
print_and_fixRetract(f"{RED}Please create the configuration file with the required parameters{RESET}")
# 使用默认值
self.forward_distance = 1.0
self.yaw_offset_deg = 0.0
except Exception as e:
print_and_fixRetract(f"{RED}Failed to load nav goal params: {e}{RESET}")
self.forward_distance = 1.0
self.yaw_offset_deg = 0.0
def timer_callback(self):
'''定时器回调函数,定期发布充电桩标记'''
# 始终发布当前JSON文件中的位置信息
if hasattr(self, 'json_data') and self.json_data:
self.Pub_Charger_marker(
self.json_data['p_x'],
self.json_data['p_y'],
self.json_data['orien_z'],
self.json_data['orien_w']
)
def check_navigation_request(self):
'''检查是否有导航请求'''
if self.navigation_requested and not self.navigation_active:
self.navigation_requested = False
self.navigation_active = True
print_and_fixRetract(f"{BLUE}Processing navigation request...{RESET}")
# 在ROS2线程中执行导航
result = self.execute_navigation_internal()
if result:
print_and_fixRetract(f"{GREEN}Navigation successful! Starting serial control...{RESET}")
# 在ROS2线程中启动串口控制
self.start_serial_control_async()
else:
print_and_fixRetract(f"{RED}Navigation failed{RESET}")
self.navigation_active = False
def request_navigation(self):
'''请求开始导航'''
if not self.navigation_active:
self.navigation_requested = True
print_and_fixRetract(f"{BLUE}Navigation request queued...{RESET}")
else:
print_and_fixRetract(f"{YELLOW}Navigation already in progress{RESET}")
def load_charger_position(self):
'''加载充电桩位置信息'''
try:
with open(json_file, 'r', encoding='utf-8') as fp:
self.json_data = json.load(fp)
print_and_fixRetract(f"Loaded charger position: x={self.json_data['p_x']:.3f}, y={self.json_data['p_y']:.3f}")
except FileNotFoundError:
print_and_fixRetract(f"{RED}Charger position file {json_file} not found{RESET}")
print_and_fixRetract(f"{RED}Please create the configuration file with default charger position{RESET}")
# 使用默认位置
self.json_data = {
'p_x': 0.0,
'p_y': 0.0,
'orien_z': 0.0,
'orien_w': 1.0
}
except Exception as e:
print_and_fixRetract(f"Error loading charger position: {e}")
self.json_data = {
'p_x': 0.0,
'p_y': 0.0,
'orien_z': 0.0,
'orien_w': 1.0
}
def save_charger_position(self):
'''保存充电桩位置信息到JSON文件'''
try:
with open(json_file, 'w', encoding='utf-8') as fp:
json.dump(self.json_data, fp, ensure_ascii=False, indent=2)
print_and_fixRetract(f"{GREEN}Charger position saved to {json_file}{RESET}")
except Exception as e:
print_and_fixRetract(f"{RED}Error saving charger position: {e}{RESET}")
def Pub_Charger_Position(self):
'''更新充电桩位置信息并保存到JSON文件'''
# 发布充电桩位置的可视化
self.Pub_Charger_marker(
self.json_data['p_x'],
self.json_data['p_y'],
self.json_data['orien_z'],
self.json_data['orien_w'])
# 保存当前充电桩位置到JSON文件
position_data = {
'p_x': self.json_data['p_x'],
'p_y': self.json_data['p_y'],
'orien_z': self.json_data['orien_z'],
'orien_w': self.json_data['orien_w']
}
self.json_data = position_data
self.save_charger_position()
print_and_fixRetract(f"Position: x={self.json_data['p_x']:.3f}, y={self.json_data['p_y']:.3f}")
def Pub_Charger_marker(self, p_x, p_y, o_z, o_w):
'''发布目标点可视化话题'''
markerArray = MarkerArray()
# 获取当前时间戳
current_time = self.get_clock().now().to_msg()
marker_shape = Marker() # 创建marker对象
marker_shape.id = 0 # 必须赋值id
marker_shape.header.frame_id = 'map' # 以哪一个TF坐标为原点
marker_shape.header.stamp = current_time # 添加时间戳
marker_shape.type = Marker.ARROW # TEXT_VIEW_FACING #一直面向屏幕的字符格式
marker_shape.action = Marker.ADD # 添加marker
marker_shape.scale.x = 0.5 # marker大小
marker_shape.scale.y = 0.05 # marker大小
marker_shape.scale.z = 0.05 # marker大小,对于字符只有z起作用
marker_shape.pose.position.x = p_x # 字符位置
marker_shape.pose.position.y = p_y # 字符位置
marker_shape.pose.position.z = 0.1 # msg.position.z #字符位置
marker_shape.pose.orientation.z = o_z # 字符位置
marker_shape.pose.orientation.w = o_w # 字符位置
marker_shape.color.r = 1.0 # 字符颜色R(红色)通道
marker_shape.color.g = 0.0 # 字符颜色G(绿色)通道
marker_shape.color.b = 0.0 # 字符颜色B(蓝色)通道
marker_shape.color.a = 1.0 # 字符透明度
markerArray.markers.append(marker_shape) # 添加元素进数组
marker_string = Marker() # 创建marker对象
marker_string.id = 1 # 必须赋值id
marker_string.header.frame_id = 'map' # 以哪一个TF坐标为原点
marker_string.header.stamp = current_time # 添加时间戳
marker_string.type = Marker.TEXT_VIEW_FACING # 一直面向屏幕的字符格式
marker_string.action = Marker.ADD # 添加marker
marker_string.scale.x = 0.5 # marker大小
marker_string.scale.y = 0.5 # marker大小
marker_string.scale.z = 0.5 # marker大小,对于字符只有z起作用
marker_string.color.a = 1.0 # 字符透明度
marker_string.color.r = 1.0 # 字符颜色R(红色)通道
marker_string.color.g = 0.0 # 字符颜色G(绿色)通道
marker_string.color.b = 0.0 # 字符颜色B(蓝色)通道
marker_string.pose.position.x = p_x # 字符位置
marker_string.pose.position.y = p_y # 字符位置
marker_string.pose.position.z = 0.1 # msg.position.z #字符位置
marker_string.pose.orientation.z = o_z # 字符位置
marker_string.pose.orientation.w = o_w # 字符位置
marker_string.text = 'Charger' # 字符内容
markerArray.markers.append(marker_string) # 添加元素进数组
self.Charger_marker_pub.publish(markerArray) # 发布markerArrayrviz订阅并进行可视化
def Position_Update_callback(self, topic):
'''更新json文件中的充电桩位置'''
position_dic = {'p_x': 0, 'p_y': 0, 'orien_z': 0, 'orien_w': 0}
position_dic['p_x'] = topic.pose.position.x
position_dic['p_y'] = topic.pose.position.y
position_dic['orien_z'] = topic.pose.orientation.z
position_dic['orien_w'] = topic.pose.orientation.w
# 保存最新的充电桩位置到json文件
self.json_data = position_dic
self.save_charger_position()
print_and_fixRetract("New charging pile position saved.")
# 位置更新后立即发布一次新的标记,然后继续定时发布
self.update_charger_visualization()
print_and_fixRetract(f"{GREEN}Charger position updated and will be published continuously{RESET}")
def update_charger_visualization(self):
'''更新充电桩可视化标记'''
if hasattr(self, 'json_data'):
self.Pub_Charger_marker(
self.json_data['p_x'],
self.json_data['p_y'],
self.json_data['orien_z'],
self.json_data['orien_w']
)
def execute_navigation(self):
"""外部调用的导航接口"""
self.request_navigation()
return True # 返回True表示请求已提交
def execute_navigation_internal(self):
"""内部执行导航任务"""
print_and_fixRetract(f"{BLUE}Starting navigation...{RESET}")
# 从JSON文件读取充电桩位置
try:
with open(json_file, 'r', encoding='utf-8') as f:
charger_data = json.load(f)
px = charger_data['p_x']
py = charger_data['p_y']
# 充电桩姿态四元数转欧拉角
orien_z = charger_data['orien_z']
orien_w = charger_data['orien_w']
yaw = 2 * math.atan2(orien_z, orien_w) # 只考虑z/w分量
except Exception as e:
print_and_fixRetract(f"{RED}Failed to read charger position file: {e}{RESET}")
self.navigation_active = False
return False
# 计算目标点位置
x_offset = self.forward_distance * math.cos(yaw)
y_offset = self.forward_distance * math.sin(yaw)
goal_x = px + x_offset
goal_y = py + y_offset
# 计算目标点姿态(z轴顺时针yaw_offset_deg
goal_yaw = yaw - math.radians(self.yaw_offset_deg)
goal_qz = math.sin(goal_yaw / 2)
goal_qw = math.cos(goal_yaw / 2)
print_and_fixRetract(f"Nav goal: x={goal_x:.3f}, y={goal_y:.3f}, yaw={math.degrees(goal_yaw):.1f}°")
goal_pose = self.create_pose(goal_x, goal_y, goal_qz, goal_qw)
# 执行导航
print_and_fixRetract(f"{BLUE}Executing navigation...{RESET}")
result1 = self.nav_through_pose([goal_pose], verbose=False)
print_and_fixRetract(f"Navigation result: {result1}")
self.navigation_active = False
return result1
def create_pose(self, x, y, z, w):
"""创建单个目标点的位姿信息"""
pose = PoseStamped()
pose.header.frame_id = 'map'
pose.header.stamp = self.get_clock().now().to_msg()
pose.pose.position.x = x
pose.pose.position.y = y
pose.pose.orientation.z = z
pose.pose.orientation.w = w
return pose
def nav_through_pose(self, goal_poses, verbose: bool = False) -> bool:
"""执行多点导航任务"""
# 开始执行多点导航任务
self.navigator.goThroughPoses(goal_poses)
# 等待导航任务完成,监控导航状态
while not self.navigator.isTaskComplete():
feedback = self.navigator.getFeedback()
if feedback and verbose:
remaining = Duration.from_msg(feedback.estimated_time_remaining).nanoseconds / 1e9
print_and_fixRetract(f"预计到达时间: {remaining:.0f}")
# 根据导航结果返回相应状态
result = self.navigator.getResult()
if result == TaskResult.SUCCEEDED:
print_and_fixRetract(f'{GREEN}Navigation successful!{RESET}')
return True
elif result == TaskResult.CANCELED:
print_and_fixRetract(f'{YELLOW}Navigation canceled!{RESET}')
elif result == TaskResult.FAILED:
print_and_fixRetract(f'{RED}Navigation failed!{RESET}')
else:
print_and_fixRetract(f'{RED}Invalid navigation result!{RESET}')
return False
def start_serial_control_async(self):
"""异步启动串口控制功能"""
def serial_control_thread():
self.start_serial_control()
# 在新线程中启动串口控制,避免阻塞ROS2主线程
serial_thread = threading.Thread(target=serial_control_thread, daemon=True)
serial_thread.start()
def start_serial_control(self):
"""启动串口控制功能"""
print_and_fixRetract(f"{BLUE}Starting serial control...{RESET}")
try:
self.parser = SerialCANParser('/dev/agvpro_ec130', 9600, 1)
self.parser.open_serial() # 打开usb串口
# 发送AT 命令从透传模式进入AT指令模式
self.parser.send_at_commands(["AT+CG", "AT+AT"])
self.serial_control_active = True
print_and_fixRetract(f'{GREEN}Serial control started successfully{RESET}')
while self.serial_control_active:
# 开始读取数据
x_speed, z_speed, which_mode, infrared_bits = self.parser.read_serial_data()
if infrared_bits[7] == 0: # 无障碍物
if which_mode == 0x01: # 正常模式
# 直接发布ROS2 Twist消息
twist_msg = Twist()
twist_msg.linear.x = float(x_speed)
twist_msg.linear.y = 0.0
twist_msg.angular.z = float(z_speed)
self.cmd_vel_pub.publish(twist_msg)
print_and_fixRetract(f'Normal mode - Speed: x={x_speed}, z={z_speed}')
elif which_mode == 0xBB: # 测压区
# 停止运动
stop_msg = Twist()
self.cmd_vel_pub.publish(stop_msg)
print_and_fixRetract(f'{YELLOW}Pressure zone - Stop movement{RESET}')
elif which_mode == 0xAA: # 充电区
# 停止运动
stop_msg = Twist()
self.cmd_vel_pub.publish(stop_msg)
print_and_fixRetract(f'{GREEN}Charging zone - Stop movement{RESET}')
break # 充电完成后退出
elif which_mode == 0xCF: # 急停模式
emergency_stop_msg = Twist() # 所有速度都为0
self.cmd_vel_pub.publish(emergency_stop_msg)
print_and_fixRetract(f'{RED}Emergency stop mode - Immediate stop{RESET}')
break
else: # 检测到障碍物
obstacle_stop_msg = Twist() # 所有速度都为0
self.cmd_vel_pub.publish(obstacle_stop_msg)
print_and_fixRetract(f'{RED}Obstacle detected - Stop movement{RESET}')
break
except KeyboardInterrupt:
print_and_fixRetract("Serial control interrupted by user")
# 发布停止消息
emergency_stop = Twist()
self.cmd_vel_pub.publish(emergency_stop)
except Exception as e:
print_and_fixRetract(f"{RED}Serial control error: {e}{RESET}")
# 发布停止消息
emergency_stop = Twist()
self.cmd_vel_pub.publish(emergency_stop)
finally:
if self.parser:
self.parser.close_serial()
print_and_fixRetract("Serial control stopped")
def stop_serial_control(self):
"""停止串口控制功能"""
self.serial_control_active = False
def get_charger_info(self):
'''获取充电桩位置信息'''
if hasattr(self, 'json_data'):
return {
'position': {
'x': self.json_data['p_x'],
'y': self.json_data['p_y']
},
'orientation': {
'z': self.json_data['orien_z'],
'w': self.json_data['orien_w']
}
}
return None
def main(args=None):
'''主函数'''
rclpy.init(args=args)
combined_recharger = None
try:
combined_recharger = CombinedAutoRecharger()
print_and_fixRetract("Combined auto recharger node is running...")
print_and_fixRetract("Node functions:")
print_and_fixRetract("- Listening for charger position updates on /charger_position_update")
print_and_fixRetract("- Publishing visualization markers on /goal_marker every 2 seconds")
print_and_fixRetract("- Press 'q' to start navigation to charger position")
print_and_fixRetract("- Navigation success will trigger serial control")
# 启动ROS2事件循环线程
def ros2_spin():
try:
rclpy.spin(combined_recharger)
except Exception as spin_error:
print_and_fixRetract(f"ROS2 spin error: {spin_error}")
ros2_thread = threading.Thread(target=ros2_spin, daemon=True)
ros2_thread.start()
# 键盘监听循环
print_and_fixRetract(f"{GREEN}Press 'q' to start navigation, Ctrl+C to exit{RESET}")
print_and_fixRetract("Waiting for keyboard input...")
while True:
try:
key = get_key(settings)
if key:
print_and_fixRetract(f"Key pressed: {repr(key)}") # 调试信息
if key.lower() == 'q':
print_and_fixRetract(f"{BLUE}Navigation command received!{RESET}")
# 请求导航任务(异步执行)
combined_recharger.execute_navigation()
elif key == '\x03': # Ctrl+C
break
time.sleep(0.1) # 避免过度占用CPU
except KeyboardInterrupt:
break
except Exception as e:
print_and_fixRetract(f"Keyboard input error: {e}")
time.sleep(0.5)
except KeyboardInterrupt:
print_and_fixRetract("\nShutting down combined auto recharger node...")
finally:
if combined_recharger:
combined_recharger.stop_serial_control()
combined_recharger.destroy_node()
rclpy.shutdown()
print_and_fixRetract("Program exited safely")
if __name__ == '__main__':
main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
#coding=UTF-8
import serial
import time
class SerialCANParser:
def __init__(self, serial_port='/dev/ttyCH341USB0', baudrate=9600, timeout=1):
self.serial_port = serial_port # 串口名称
self.baudrate = baudrate # 波特率
self.timeout = timeout # 超时设置
self.ser = None # 串口对象
self.buffer = bytearray() # 存储当前读取的字节
self.max_retries = 3 # 最大重试次数
# 存储实时数据
self.x_speed = 0.0
self.z_speed = 0.0
self.infrared_bits = []
def open_serial(self):
"""打开串口"""
try:
self.ser = serial.Serial(self.serial_port, self.baudrate, timeout=self.timeout)
print(f"串口 {self.serial_port} 已打开,波特率:{self.baudrate}")
except Exception as e:
print(f"打开串口失败: {e}")
def close_serial(self):
"""关闭串口"""
if self.ser and self.ser.is_open:
self.ser.close()
print("串口已关闭。")
else:
print("串口未打开或已关闭。")
def can_id_check(self, date):
high_byte, low_byte = date[0:2]
# 高字节左移 3 位
can_id = (high_byte << 3)
# 低字节右移 5 位
can_id |= (low_byte >> 5)
return can_id
def parse_can_data(self, data):
"""解析8字节CAN数据帧"""
if len(data) != 8:
print("数据帧长度不正确")
return None
# 解析 X、Y 和 Z 速度
x_speed_raw = ((data[0] << 8) | data[1]) # X速度的原始数据
z_speed_raw = ((data[4] << 8) | data[5]) # Z速度的原始数据
# 将原始数据转换为浮动数值,并考虑正负
if x_speed_raw & 0x8000: # 如果最高位为1,表示负数
x_speed_raw = -((65536 - x_speed_raw) & 0xFFFF) # 补码转换为负数
if z_speed_raw & 0x8000: # 如果最高位为1,表示负数
z_speed_raw = -((65536 - z_speed_raw) & 0xFFFF) # 补码转换为负数
# 转换单位为 m/s 和 rad/s
self.x_speed = x_speed_raw / 1000.0 # X速度单位为 m/s
self.y_speed = 0 # Y速度为0
self.z_speed = z_speed_raw / 1000.0 # Z速度单位为 rad/s
self.which_mode = data[2]
self.infrared = data[6] # 红外数据
self.raw_current = data[7] # 电流数据
if self.raw_current > 32767: # 无符号数大于 32767 表示负值(因为最大值是 65535)
# 转换为负数
self.actual_current = -(65536 - self.raw_current) * 30.0
else:
# 正数直接转换
self.actual_current = self.raw_current * 30.0
# 处理红外数据
self.infrared_bits = [(self.infrared >> (7 - i)) & 0x01 for i in range(8)]
# 打印或处理数据
print(f"X Speed: {self.x_speed:.3f}, Y Speed: {self.y_speed}, Z Speed: {self.z_speed:.3f}, "
f"Actual Current: {self.actual_current:.3f} mA, Infrared: {self.infrared}")
# 打印或处理红外位信息
print(f"L_A: {self.infrared_bits[2]}, L_B: {self.infrared_bits[3]}, R_B: {self.infrared_bits[4]}, "
f"R_A: {self.infrared_bits[5]}, infrared_flag : {self.infrared_bits[6]}, "
f"Charging flag: {self.infrared_bits[7]}")
def read_serial_data(self):
"""读取串口数据并解析"""
while True: # 修改为简单的无限循环,由上层控制退出
if self.ser.in_waiting > 0:
byte = self.ser.read(1) # 读取一个字节
if len(self.buffer) < 2:
self.buffer.extend(byte)
if len(self.buffer) == 2:
# 如果帧头为 0x41 0x54,表示为AT帧头,则开始接收数据
if self.buffer[0] != 0x41 or self.buffer[1] != 0x54:
# 如果不是有效的帧头,则清空缓冲区并跳到下次循环
self.buffer.clear()
continue # 继续等待下一个字节
else:
self.buffer.extend(byte)
# print("缓冲区内容:", ' '.join(f'{b:02x}' for b in self.buffer)) # debug
# 如果缓冲区字节长度大于等于 17 字节(数据帧长度)
if len(self.buffer) >= 17:
# print("Received Frame (Hex):", ' '.join(f'{byte:02x}' for byte in self.buffer)) # debug
# 解析帧头、CAN帧ID、格式、类型和数据
# at_frame_header = self.buffer[0:2] # AT帧头
can_frame_id = self.can_id_check(self.buffer[2:4]) # CAN标准帧ID
# can_frame_format = self.buffer[4] # CAN帧格式(0,标准帧;1,扩展帧)
# can_frame_type = self.buffer[5] # CAN帧类型(0,数据帧;1,远程帧)
data_length = self.buffer[6] # 数据长度
data = self.buffer[7:15] # 数据帧
# print(f"帧ID: 0x{can_frame_id:X}") # debug
if can_frame_id == 0x182 and data_length == 0x08: # 根据can帧id进行判断
# 如果帧ID为0x182,校验通过,进行数据赋值
self.parse_can_data(data)
# 清空缓冲区,准备下一帧数据
self.buffer.clear()
return self.x_speed, self.z_speed, self.which_mode, self.infrared_bits # 返回解析后的数据
else:
# 清空缓冲区,准备下一帧数据
self.buffer.clear()
def read_serial_response(self):
"""读取串口响应数据,直到接收到 '\r\n' 或超时"""
response = bytearray() # 使用 bytearray 来存储原始字节流
while True:
if self.ser.in_waiting > 0:
byte = self.ser.read(1)
response += byte
# 检查是否已接收到完整响应
if b'\r\n' in response:
break
# 超时机制,防止死循环
if len(response) > 100:
break
return bytes(response) # 返回原始字节流(bytes
def send_at_commands(self, commands):
"""发送 AT 命令并等待响应"""
for command in commands:
retries = 0
while retries < self.max_retries:
self.ser.write(command.encode() + b'\r\n')
print(f"发送命令: {command}")
# 等待响应并读取数据
response = self.read_serial_response()
# 检查响应是否包含 "OK"
if b"OK" in response:
print(f"收到响应: {response}")
break # 如果收到 OK,退出重试循环
else:
retries += 1
print(f"未收到预期的响应,收到: {response}")
if retries == self.max_retries:
print(f"重试 {self.max_retries} 次后仍未收到有效响应,请检查设备。")
break
def start(self):
"""开始读取和处理数据"""
self.open_serial()
try:
# 发送AT 命令从透传模式进入AT指令模式
self.send_at_commands(["AT+CG", "AT+AT"])
# 开始读取数据
self.read_serial_data()
except KeyboardInterrupt:
print("手动中止程序。")
finally:
self.close_serial()
if __name__ == '__main__':
parser = SerialCANParser('/dev/ttyCH341USB0', 9600, 1)
parser.start()
+6
View File
@@ -0,0 +1,6 @@
{
"p_x": -0.04373347759246826,
"p_y": -4.024151802062988,
"orien_z": 0.09378381732290733,
"orien_w": 0.9955925851513477
}
+3
View File
@@ -0,0 +1,3 @@
# 导航参数配置
forward_distance: 1 # 距离充电桩前方1米
yaw_offset_deg: 10.0 # 顺时针旋转10度
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_autocharge</name>
<version>1.0.8</version>
<description>AGV automatic charging system for ROS2 Humble</description>
<maintainer email="your-email@example.com">Your Name</maintainer>
<license>MIT</license>
<!-- Build dependencies -->
<buildtool_depend>ament_python</buildtool_depend>
<!-- Runtime dependencies -->
<depend>rclpy</depend>
<depend>geometry_msgs</depend>
<depend>std_msgs</depend>
<depend>nav_msgs</depend>
<depend>visualization_msgs</depend>
<depend>nav2_simple_commander</depend>
<!-- Test dependencies -->
<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>
<test_depend>ament_pep257</test_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
+1
View File
@@ -0,0 +1 @@
agv_pro_autocharge
+4
View File
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/agv_pro_autocharge
[install]
install_scripts=$base/lib/agv_pro_autocharge
+30
View File
@@ -0,0 +1,30 @@
from setuptools import setup, find_packages
import os
from glob import glob
package_name = 'agv_pro_autocharge'
setup(
name=package_name,
version='1.0.0',
packages=find_packages(),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
# Include config files
(os.path.join('share', package_name, 'config'), glob('config/*')),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Your Name',
maintainer_email='your-email@example.com',
description='AGV automatic charging system for ROS2 Humble',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'combined_auto_recharger = agv_pro_autocharge.combined_auto_recharger:main',
],
},
)
+2
View File
@@ -17,6 +17,7 @@ find_package(tf2_geometry_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(agv_pro_msgs REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)
@@ -42,6 +43,7 @@ ament_target_dependencies(agv_pro_node
geometry_msgs
serial_driver
nav_msgs
agv_pro_msgs
)
install(TARGETS agv_pro_node
@@ -13,11 +13,23 @@
#include <tf2_ros/transform_broadcaster.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <agv_pro_msgs/srv/set_digital_output.hpp>
#include <agv_pro_msgs/srv/get_digital_input.hpp>
#include <agv_pro_msgs/srv/set_led_color.hpp>
#include <agv_pro_msgs/srv/set_led_mode.hpp>
#define SEND_DATA_SIZE 14 // Total bytes in a command frame to ESP32(version>=V1.0.8)
#define RECEIVE_FRAME_SIZE 31 // Total bytes in a frame from ESP32(version>=V1.0.8)
#define RECEIVE_PAYLOAD_SIZE (RECEIVE_FRAME_SIZE - 3) // Payload length (excluding header)
#define POWER_ON 0x10
#define GET_POWER_STATE 0x12
#define SET_AUTO_REPORT_STATE 0x23
#define SET_LED_COLOR 0x34
#define SET_LED_MODE 0x3A
#define SET_OUTPUT_IO 0x40
#define GET_INPUT_IO 0x41
extern std::array<double, 36> odom_pose_covariance;
extern std::array<double, 36> odom_twist_covariance;
@@ -152,6 +164,50 @@ private:
*/
uint16_t crc16_ibm(const uint8_t* data, size_t length);
/**
* @brief Handle the SetDigitalOutput service request.
*
* This service sets the state (HIGH/LOW) of a specific digital output pin on the AGV device.
* The request contains the pin number and desired state, which are sent to the hardware
* via the serial interface. The response reports whether the operation succeeded.
*
* @param[in] request The service request, containing:
* - pin: The digital output pin number.
* - state: Desired output state (true = HIGH, false = LOW).
* @param[out] response The service response, containing:
* - success: True if the operation succeeded.
* - message: Optional status or error description.
*/
void handleSetDigitalOutput(
const std::shared_ptr<agv_pro_msgs::srv::SetDigitalOutput::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetDigitalOutput::Response> response);
/**
* @brief Handle the GetDigitalInput service request.
*
* This service reads the state (HIGH/LOW) of a specific digital input pin on the AGV device.
* The request specifies the pin number, and the node queries the hardware via the serial
* interface to retrieve its current state.
*
* @param[in] request The service request, containing:
* - pin: The digital input pin number to read.
* @param[out] response The service response, containing:
* - state: Current pin state (true = HIGH, false = LOW).
* - success: True if the read operation succeeded.
* - message: Optional status or error description.
*/
void handleGetDigitalInput(
const std::shared_ptr<agv_pro_msgs::srv::GetDigitalInput::Request> request,
std::shared_ptr<agv_pro_msgs::srv::GetDigitalInput::Response> response);
void handleSetLedColor(
const std::shared_ptr<agv_pro_msgs::srv::SetLedColor::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetLedColor::Response> response);
void handleSetLedMode(
const std::shared_ptr<agv_pro_msgs::srv::SetLedMode::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetLedMode::Response> response);
boost::asio::io_service io_;
std::unique_ptr<boost::asio::serial_port> serial_port_;
@@ -216,6 +272,10 @@ private:
rclcpp::Publisher<sensor_msgs::msg::Imu>::SharedPtr pub_imu;
rclcpp::Publisher<std_msgs::msg::Float32>::SharedPtr pub_voltage;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr cmd_sub;
rclcpp::Service<agv_pro_msgs::srv::SetDigitalOutput>::SharedPtr set_output_service;
rclcpp::Service<agv_pro_msgs::srv::GetDigitalInput>::SharedPtr get_input_service;
rclcpp::Service<agv_pro_msgs::srv::SetLedColor>::SharedPtr set_led_service;
rclcpp::Service<agv_pro_msgs::srv::SetLedMode>::SharedPtr set_led_mode_service;
sensor_msgs::msg::Imu imu_data;
std::unique_ptr<tf2_ros::TransformBroadcaster> odomBroadcaster;
+2 -1
View File
@@ -2,7 +2,7 @@
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_base</name>
<version>1.0.3</version>
<version>1.0.8</version>
<description>Control Nodes for AGV Pro</description>
<maintainer email="weijun.xie@elephantrobotics.com">lanni</maintainer>
<license>BSD-3-Clause license</license>
@@ -16,6 +16,7 @@
<depend>asio_cmake_module</depend>
<depend>io_context</depend>
<depend>tf2_geometry_msgs</depend>
<depend>agv_pro_msgs</depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
+193 -12
View File
@@ -117,7 +117,7 @@ std::vector<uint8_t> AGV_PRO::read_serial_response(
}
bool AGV_PRO::is_power_on(){
auto power_query_frame = build_serial_frame(0x12, {});
auto power_query_frame = build_serial_frame(GET_POWER_STATE, {});
send_serial_frame(power_query_frame,true);
const std::vector<uint8_t> expected_header = {0xFE, 0xFE, 0x0B, 0x12};
@@ -138,7 +138,7 @@ bool AGV_PRO::is_power_on(){
RCLCPP_INFO(this->get_logger(), "is_poweron_status: %d", is_poweron_status);
if (is_poweron_status == 0){
auto status_query_frame = build_serial_frame(0x10, {});
auto status_query_frame = build_serial_frame(POWER_ON, {});
send_serial_frame(status_query_frame,true);
rclcpp::sleep_for(std::chrono::milliseconds(1000));// Sleep for 1000 milliseconds to allow the device enough time to process the previous command
@@ -256,6 +256,155 @@ void AGV_PRO::cmdCallback(const geometry_msgs::msg::Twist::SharedPtr msg)
}
}
void AGV_PRO::handleSetDigitalOutput(
const std::shared_ptr<agv_pro_msgs::srv::SetDigitalOutput::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetDigitalOutput::Response> response)
{
uint8_t output_number = request->pin;
uint8_t output_state = request->state;
if (output_number < 1 || output_number > 6){
RCLCPP_ERROR(this->get_logger(), "Invalid output pin number: %u", output_number);
response->success = false;
response->message = "Invalid output pin number";
return;
}
auto frame = build_serial_frame(SET_OUTPUT_IO, {output_number, output_state});
send_serial_frame(frame, true);
const std::vector<uint8_t> expected_header = {0xFE, 0xFE, 0x0B, SET_OUTPUT_IO};
auto response_frame = read_serial_response(expected_header, 8, 5.0);
// print_hex("recv_buf", response_frame); //debug
uint8_t status = response_frame[4];
if (status == 0x01) {
RCLCPP_DEBUG(this->get_logger(), "SetDigitalOutput succeeded");
response->success = true;
response->message = "Success";
} else {
RCLCPP_ERROR(this->get_logger(), "SetDigitalOutput failed with status: 0x%02X", status);
response->success = false;
response->message = "Failed with status code";
}
}
void AGV_PRO::handleGetDigitalInput(
const std::shared_ptr<agv_pro_msgs::srv::GetDigitalInput::Request> request,
std::shared_ptr<agv_pro_msgs::srv::GetDigitalInput::Response> response)
{
uint8_t input_number = request->pin;
if (input_number < 1 || input_number > 6){
RCLCPP_ERROR(this->get_logger(), "Invalid input pin number: %u", input_number);
response->success = false;
response->message = "Invalid input pin number";
return;
}
auto frame = build_serial_frame(GET_INPUT_IO, {input_number});
send_serial_frame(frame, true);
const std::vector<uint8_t> expected_header = {0xFE, 0xFE, 0x0B, GET_INPUT_IO};
auto response_frame = read_serial_response(expected_header, 8, 5.0);
// print_hex("recv_buf", response_frame); //debug
uint8_t status = response_frame[5];
if (status == 0xff) {
RCLCPP_ERROR(this->get_logger(), "GetDigitalInput failed with status: 0x%02X", status);
response->success = false;
} else {
RCLCPP_DEBUG(this->get_logger(), "GetDigitalInput succeeded, state: %u", status);
response->state = static_cast<int32_t>(status);
response->success = true;
response->message = "Success";
}
}
void AGV_PRO::handleSetLedColor(
const std::shared_ptr<agv_pro_msgs::srv::SetLedColor::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetLedColor::Response> response)
{
if (request->position < 0 || request->position > 1) {
RCLCPP_ERROR(this->get_logger(), "Invalid LED position: %d", request->position);
response->success = false;
response->message = "Invalid LED position";
return;
}
if (request->brightness < 0 || request->brightness > 255) {
RCLCPP_ERROR(this->get_logger(), "Invalid brightness: %d", request->brightness);
response->success = false;
response->message = "Invalid brightness";
return;
}
if (request->r < 0 || request->r > 255 ||
request->g < 0 || request->g > 255 ||
request->b < 0 || request->b > 255) {
RCLCPP_ERROR(
this->get_logger(),
"Invalid RGB value: r=%d g=%d b=%d",
request->r, request->g, request->b
);
response->success = false;
response->message = "Invalid RGB value";
return;
}
uint8_t position = static_cast<uint8_t>(request->position);
uint8_t brightness = static_cast<uint8_t>(request->brightness);
uint8_t r = static_cast<uint8_t>(request->r);
uint8_t g = static_cast<uint8_t>(request->g);
uint8_t b = static_cast<uint8_t>(request->b);
auto frame = build_serial_frame(SET_LED_COLOR, {position, brightness, r, g, b});
send_serial_frame(frame, true);
const std::vector<uint8_t> expected_header = {0xFE, 0xFE, 0x0B, SET_LED_COLOR};
auto response_frame = read_serial_response(expected_header, 8, 5.0);
// print_hex("recv_buf", response_frame); //debug
uint8_t status = response_frame[4];
if (status == 0x01) {
RCLCPP_DEBUG(this->get_logger(), "SetLedColor succeeded");
response->success = true;
response->message = "Success";
} else {
RCLCPP_ERROR(this->get_logger(), "SetLedColor failed with status: 0x%02X", status);
response->success = false;
response->message = "Failed with status code";
}
}
void AGV_PRO::handleSetLedMode(
const std::shared_ptr<agv_pro_msgs::srv::SetLedMode::Request> request,
std::shared_ptr<agv_pro_msgs::srv::SetLedMode::Response> response)
{
uint8_t mode = request->mode ? 0x01 : 0x00;
auto frame = build_serial_frame(SET_LED_MODE, {mode});
send_serial_frame(frame, true);
const std::vector<uint8_t> expected_header = {0xFE, 0xFE, 0x0B, SET_LED_MODE};
auto response_frame = read_serial_response(expected_header, 8, 5.0);
// print_hex("recv_buf", response_frame); //debug
uint8_t status = response_frame[4];
if (status == 0x01) {
RCLCPP_DEBUG(this->get_logger(), "SetLedMode succeeded");
response->success = true;
response->message = "Success";
} else {
RCLCPP_ERROR(this->get_logger(), "SetLedMode failed with status: 0x%02X", status);
response->success = false;
response->message = "Failed with status code";
}
}
bool AGV_PRO::readData()
{
std::vector<uint8_t> buf_length(1);
@@ -309,7 +458,7 @@ bool AGV_PRO::readData()
recv_buf.push_back(0x1C);
recv_buf.insert(recv_buf.end(), data_buf.begin(), data_buf.end());
//print_hex("recv_buf", recv_buf); //debug
// print_hex("recv_buf", recv_buf); //debug
if (recv_buf[3] != 0x25) {
//RCLCPP_WARN(this->get_logger(), "Command error:0x%02X", recv_buf[2]); //debug
@@ -333,17 +482,29 @@ bool AGV_PRO::readData()
battery_voltage = static_cast<float>(recv_buf[9]) / 10.0f;
enable_status = recv_buf[10];
imu_data.linear_acceleration.x = static_cast<double>((static_cast<int16_t>(recv_buf[11]) << 8) | recv_buf[12]) * 0.01;
imu_data.linear_acceleration.y = static_cast<double>((static_cast<int16_t>(recv_buf[13]) << 8) | recv_buf[14]) * 0.01;
imu_data.linear_acceleration.z = static_cast<double>((static_cast<int16_t>(recv_buf[15]) << 8) | recv_buf[16]) * 0.01;
imu_data.linear_acceleration.x = static_cast<double>(static_cast<int16_t>((recv_buf[11] << 8) | recv_buf[12])) * 0.01;
imu_data.linear_acceleration.y = static_cast<double>(static_cast<int16_t>((recv_buf[13] << 8) | recv_buf[14])) * 0.01;
imu_data.linear_acceleration.z = static_cast<double>(static_cast<int16_t>((recv_buf[15] << 8) | recv_buf[16])) * 0.01;
imu_data.angular_velocity.x = static_cast<double>((static_cast<int16_t>(recv_buf[17]) << 8) | recv_buf[18]) * 0.01;
imu_data.angular_velocity.y = static_cast<double>((static_cast<int16_t>(recv_buf[19]) << 8) | recv_buf[20]) * 0.01;
imu_data.angular_velocity.z = static_cast<double>((static_cast<int16_t>(recv_buf[21]) << 8) | recv_buf[22]) * 0.01;
imu_data.angular_velocity.x = static_cast<double>(static_cast<int16_t>((recv_buf[17] << 8) | recv_buf[18])) * 0.01;
imu_data.angular_velocity.y = static_cast<double>(static_cast<int16_t>((recv_buf[19] << 8) | recv_buf[20])) * 0.01;
imu_data.angular_velocity.z = static_cast<double>(static_cast<int16_t>((recv_buf[21] << 8) | recv_buf[22])) * 0.01;
roll = static_cast<double>((static_cast<int16_t>(recv_buf[23]) << 8) | recv_buf[24]) * 0.01;
pitch = static_cast<double>((static_cast<int16_t>(recv_buf[25]) << 8) | recv_buf[26]) * 0.01;
yaw = static_cast<double>((static_cast<int16_t>(recv_buf[27]) << 8) | recv_buf[28]) * 0.01;
roll = static_cast<double>(static_cast<int16_t>((recv_buf[23] << 8) | recv_buf[24])) * 0.01;
pitch = static_cast<double>(static_cast<int16_t>((recv_buf[25] << 8) | recv_buf[26])) * 0.01;
yaw = static_cast<double>(static_cast<int16_t>((recv_buf[27] << 8) | recv_buf[28])) * 0.01;
// RCLCPP_INFO(this->get_logger(),
// "IMU Data - Accel[x: %.2f, y: %.2f, z: %.2f], "
// "Gyro[x: %.2f, y: %.2f, z: %.2f], "
// "RPY[roll: %.2f, pitch: %.2f, yaw: %.2f]",
// imu_data.linear_acceleration.x,
// imu_data.linear_acceleration.y,
// imu_data.linear_acceleration.z,
// imu_data.angular_velocity.x,
// imu_data.angular_velocity.y,
// imu_data.angular_velocity.z,
// roll, pitch, yaw);
return true;
}
@@ -481,6 +642,26 @@ AGV_PRO::AGV_PRO(std::string node_name):rclcpp::Node(node_name)
cmd_sub = this->create_subscription<geometry_msgs::msg::Twist>(
"/cmd_vel", 10, std::bind(&AGV_PRO::cmdCallback, this, std::placeholders::_1));
set_output_service = this->create_service<agv_pro_msgs::srv::SetDigitalOutput>(
"set_digital_output",
std::bind(&AGV_PRO::handleSetDigitalOutput, this, std::placeholders::_1, std::placeholders::_2)
);
get_input_service = this->create_service<agv_pro_msgs::srv::GetDigitalInput>(
"get_digital_input",
std::bind(&AGV_PRO::handleGetDigitalInput, this, std::placeholders::_1, std::placeholders::_2)
);
set_led_service = this->create_service<agv_pro_msgs::srv::SetLedColor>(
"set_led_color",
std::bind(&AGV_PRO::handleSetLedColor, this, std::placeholders::_1, std::placeholders::_2)
);
set_led_mode_service = this->create_service<agv_pro_msgs::srv::SetLedMode>(
"set_led_mode",
std::bind(&AGV_PRO::handleSetLedMode, this, std::placeholders::_1, std::placeholders::_2)
);
lastTime = this->get_clock()->now();
try{
@@ -1,15 +1,36 @@
import os
from launch import LaunchDescription
from launch.conditions import IfCondition
from launch_ros.actions import Node,PushRosNamespace
from launch.actions import DeclareLaunchArgument,IncludeLaunchDescription
from launch.substitutions import Command,LaunchConfiguration,PythonExpression
from launch.launch_description_sources import PythonLaunchDescriptionSource
from ament_index_python.packages import get_package_share_directory
def include_lidar(pkg_name, launch_file, enable_lidar, lidar_type, expected_type):
return IncludeLaunchDescription(
PythonLaunchDescriptionSource(
os.path.join(
get_package_share_directory(pkg_name),
'launch',
launch_file
)
),
condition=IfCondition(
PythonExpression([
"'", enable_lidar, "' == 'true' and '",
lidar_type, "' == '", expected_type, "'"
])
)
)
def generate_launch_description():
port_name_arg = LaunchConfiguration('port_name',default='/dev/agvpro_controller')
namespace = LaunchConfiguration('namespace', default='')
port_name_arg = LaunchConfiguration('port_name')
namespace = LaunchConfiguration('namespace')
lidar_type = LaunchConfiguration('lidar_type')
enable_lidar = LaunchConfiguration('enable_lidar')
urdf_file = os.path.join(
get_package_share_directory('agv_pro_description'),
@@ -24,48 +45,74 @@ def generate_launch_description():
PythonExpression(['"', namespace, '" + "/" if "', namespace, '" != "" else ""']),
])
return LaunchDescription([
DeclareLaunchArgument(
'port_name',
default_value=port_name_arg,
description='port name, e.g. ttyACM0'),
declare_port_name_arg = DeclareLaunchArgument(
'port_name',
default_value='/dev/agvpro_controller',
description='port name, e.g. /dev/ttyACM0'
)
DeclareLaunchArgument(
'namespace',
default_value='',
description='Namespace for nodes'),
declare_namespace_arg = DeclareLaunchArgument(
'namespace',
default_value='',
description='Namespace for nodes'
)
PushRosNamespace(namespace),
declare_enable_lidar_arg = DeclareLaunchArgument(
'enable_lidar',
default_value='true',
description='Whether to launch lidar drivers'
)
Node(
package='agv_pro_base',
executable='agv_pro_node',
name='agv_pro_node',
output='screen',
parameters=[{
'port_name': port_name_arg,
'namespace': namespace,
}],
remappings=[('cmd_vel', '/cmd_vel')]
),
declare_lidar_type_arg = DeclareLaunchArgument(
'lidar_type',
default_value='n10p',
description='Lidar type: n10p | mid360 | l2'
)
Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher'
),
ns_action = PushRosNamespace(namespace)
Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[{'robot_description': robot_description_content}],
output='screen'
),
agv_pro_node = Node(
package='agv_pro_base',
executable='agv_pro_node',
name='agv_pro_node',
output='screen',
parameters=[{
'port_name': port_name_arg,
'namespace': namespace,
}],
remappings=[('cmd_vel', '/cmd_vel')]
)
IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
get_package_share_directory('lslidar_driver'),'launch'),
'/lsn10p_launch.py'])
)
])
joint_state_pub = Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher'
)
robot_state_pub = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[{'robot_description': robot_description_content}],
output='screen'
)
lidar_launchs = [
include_lidar('lslidar_driver', 'lsn10p_launch.py', enable_lidar, lidar_type, 'n10p'),
include_lidar('livox_ros_driver2', 'MID360_launch.py',enable_lidar, lidar_type, 'mid360'),
include_lidar('unitree_lidar_ros2', 'launch.py', enable_lidar, lidar_type, 'l2'),
]
return LaunchDescription(
[
declare_port_name_arg,
declare_namespace_arg,
declare_enable_lidar_arg,
declare_lidar_type_arg,
ns_action,
agv_pro_node,
joint_state_pub,
robot_state_pub,
*lidar_launchs,
]
)
+1 -1
View File
@@ -2,7 +2,7 @@
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_bringup</name>
<version>1.0.0</version>
<version>1.0.8</version>
<description>ROS 2 launch scripts for starting the AGV Pro</description>
<maintainer email="weijun.xie@elephantrobotics.com">lanni</maintainer>
<license>BSD-3-Clause license</license>
@@ -0,0 +1,388 @@
#!/usr/bin/env python3
"""Yaw-only final pose refinement helper for AGV Pro."""
import math
import os
import shlex
import rclpy
from action_msgs.msg import GoalStatus, GoalStatusArray
from geometry_msgs.msg import PoseStamped, Twist
from rclpy.duration import Duration
from rclpy.node import Node
from rclpy.parameter import Parameter
from std_msgs.msg import String
from tf2_ros import Buffer, TransformException, TransformListener
class FinalPoseRefiner(Node):
"""Refine only the final map->base_footprint yaw with direct low-speed cmd_vel."""
def __init__(self):
super().__init__('final_pose_refiner')
self.param_prefix = 'final_pose_refiner_'
self.start_param = f'{self.param_prefix}start'
self.cancel_param = f'{self.param_prefix}cancel'
self.auto_start_param = f'{self.param_prefix}auto_start_on_nav_success'
self.log_separator = '------------------------------------------------------------'
self.cmd_vel_topic = '/cmd_vel'
self.goal_topic = '/goal_pose'
self.action_goal_topic = '/final_pose_refiner/goal_pose'
self.nav_status_topic = '/navigate_to_pose/_action/status'
self.nav2_status_topic = '/navigate_to_pose_nav2/_action/status'
self.global_frame = 'map'
self.base_frame = 'base_footprint'
self._declare_param('status_topic', '/final_pose_refiner/status')
self.declare_parameter(self.start_param, False)
self.declare_parameter(self.cancel_param, False)
self.declare_parameter(self.auto_start_param, False)
self._declare_param('handoff_distance', 0.20)
self._declare_param('yaw_tolerance', 0.04)
self._declare_param('settle_time', 0.5)
self._declare_param('timeout', 20.0)
self._declare_param('k_yaw', 0.5)
self._declare_param('max_wz', 0.35)
self._declare_param('min_cmd_w', 0.006)
self.cmd_vel_pub = self.create_publisher(Twist, self.cmd_vel_topic, 10)
self.status_pub = self.create_publisher(String, self._param('status_topic'), 10)
self.goal_sub = self.create_subscription(
PoseStamped,
self.goal_topic,
self._on_goal,
10,
)
self.action_goal_sub = self.create_subscription(
PoseStamped,
self.action_goal_topic,
self._on_goal,
10,
)
self.nav_status_sub = self.create_subscription(
GoalStatusArray,
self.nav_status_topic,
self._on_nav_status,
10,
)
self.nav2_status_sub = self.create_subscription(
GoalStatusArray,
self.nav2_status_topic,
self._on_nav_status,
10,
)
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.state = 'idle'
self.goal = None
self.target = None
self.waiting_for_nav_success = False
self.active_nav_goal_ids = set()
self.refined_nav_goal_ids = set()
self.start_time = None
self.settle_start_time = None
self.last_log_time = self.get_clock().now()
self.timer = self.create_timer(1.0 / 20.0, self.on_timer)
self.get_logger().info(
'final_pose_refiner ready in yaw-only mode. A navigation proxy may submit the '
f'target and set {self.start_param}:=true, or these may be provided manually.'
)
def _declare_param(self, name, value):
self.declare_parameter(f'{self.param_prefix}{name}', value)
def _param(self, name):
return self.get_parameter(f'{self.param_prefix}{name}').value
def _on_goal(self, msg):
if msg.header.frame_id and msg.header.frame_id != self.global_frame:
self.get_logger().warn(
f'Ignoring goal in frame "{msg.header.frame_id}". Expected "{self.global_frame}".'
)
return
q = msg.pose.orientation
target_yaw = self._yaw_from_quaternion(q.x, q.y, q.z, q.w)
self.target = (msg.pose.position.x, msg.pose.position.y, target_yaw)
self.waiting_for_nav_success = True
self.active_nav_goal_ids.clear()
self.get_logger().info(
f'Updated refine target from topic: x={msg.pose.position.x:.4f}, '
f'y={msg.pose.position.y:.4f}, yaw={math.degrees(target_yaw):.2f} deg'
)
def _on_nav_status(self, msg):
if not self.get_parameter(self.auto_start_param).value:
return
if self.state != 'idle' or self.target is None or not self.waiting_for_nav_success:
return
for status in msg.status_list:
goal_id = tuple(status.goal_info.goal_id.uuid)
if status.status in (GoalStatus.STATUS_ACCEPTED, GoalStatus.STATUS_EXECUTING):
self.active_nav_goal_ids.add(goal_id)
elif status.status == GoalStatus.STATUS_SUCCEEDED:
if (
goal_id in self.active_nav_goal_ids and
goal_id not in self.refined_nav_goal_ids
):
self.refined_nav_goal_ids.add(goal_id)
self.get_logger().info(
'Detected Nav2 goal succeeded; starting final yaw refinement.'
)
self._start_refine()
return
elif status.status in (GoalStatus.STATUS_CANCELED, GoalStatus.STATUS_ABORTED):
if goal_id in self.active_nav_goal_ids:
self.waiting_for_nav_success = False
self.active_nav_goal_ids.discard(goal_id)
def on_timer(self):
if self.get_parameter(self.cancel_param).value:
if self.state == 'running':
self._finish_refine('canceled')
else:
self._reset_cancel_refine()
return
if self.state == 'running':
self._run_refine_step()
return
if self.get_parameter(self.start_param).value:
self._start_refine()
def _start_refine(self):
self._reset_cancel_refine()
if self.target is None:
self.get_logger().warn(
'Cannot start final refinement: no /goal_pose has been received yet.'
)
self._publish_status('no_goal')
self._reset_start_refine()
return
pose = self._lookup_pose()
if pose is None:
self.get_logger().warn('Cannot start final refinement: TF is not available.')
self._publish_status('failed_tf')
self._reset_start_refine()
return
target = self.target
distance, yaw_error = self._calculate_error(pose, target)
handoff_distance = max(self._param('handoff_distance'), 0.0)
if distance > handoff_distance:
self.get_logger().warn(
f'Cannot start final refinement: distance={distance:.3f} m exceeds '
f'handoff_distance={handoff_distance:.3f} m.'
)
self._publish_status('handoff_distance_exceeded')
self._reset_start_refine()
return
self.goal = target
self.waiting_for_nav_success = False
self.start_time = self.get_clock().now()
self.settle_start_time = None
self.last_log_time = self.get_clock().now()
self.state = 'running'
self._publish_status('running')
self.get_logger().info(
f'\n{self.log_separator}\n'
'FINAL YAW REFINE START\n'
f'target=({target[0]:.4f}, {target[1]:.4f}, {math.degrees(target[2]):.2f} deg)\n'
f'initial_distance={distance:.3f} m, '
f'initial_yaw_error={math.degrees(yaw_error):+.2f} deg\n'
f'{self.log_separator}'
)
def _run_refine_step(self):
pose = self._lookup_pose()
if pose is None:
self._finish_refine('failed_tf', warn=True)
return
distance, yaw_error = self._calculate_error(pose, self.goal)
elapsed = (self.get_clock().now() - self.start_time).nanoseconds / 1e9
yaw_tolerance = max(self._param('yaw_tolerance'), 0.0)
settle_time = max(self._param('settle_time'), 0.0)
timeout = self._param('timeout')
if timeout > 0.0 and elapsed > timeout:
self._finish_refine('timeout', pose, distance, yaw_error, warn=True)
return
if abs(yaw_error) <= yaw_tolerance:
now = self.get_clock().now()
if self.settle_start_time is None:
self.settle_start_time = now
self._publish_stop()
elif (now - self.settle_start_time).nanoseconds / 1e9 >= settle_time:
self._finish_refine('succeeded', pose, distance, yaw_error)
return
else:
self._publish_stop()
self._log_progress(pose, distance, yaw_error, elapsed, Twist())
return
self.settle_start_time = None
cmd = self._make_yaw_command(yaw_error)
self.cmd_vel_pub.publish(cmd)
self._log_progress(pose, distance, yaw_error, elapsed, cmd)
def _make_yaw_command(self, yaw_error):
cmd = Twist()
max_wz = max(abs(self._param('max_wz')), 0.0)
cmd.angular.z = self._clip(self._param('k_yaw') * yaw_error, -max_wz, max_wz)
cmd.angular.z = self._apply_min_abs(cmd.angular.z, self._param('min_cmd_w'))
return cmd
def _finish_refine(self, status, pose=None, distance=None, yaw_error=None, warn=False):
self._stop_robot()
self._reset_start_refine()
self._reset_cancel_refine()
self.state = 'idle'
self.settle_start_time = None
self._publish_status(status)
if pose is not None and distance is not None and yaw_error is not None:
msg = (
f'\n{self.log_separator}\n'
f'FINAL YAW REFINE END: {status}\n'
f'distance={distance:.4f} m, '
f'yaw_error={math.degrees(yaw_error):+.2f} deg, '
f'pose=({pose[0]:.4f}, {pose[1]:.4f}, {math.degrees(pose[2]):.2f} deg)\n'
f'{self.log_separator}'
)
else:
msg = (
f'\n{self.log_separator}\n'
f'FINAL YAW REFINE END: {status}\n'
f'{self.log_separator}'
)
if warn:
self.get_logger().warn(msg)
else:
self.get_logger().info(msg)
def _lookup_pose(self):
try:
trans = self.tf_buffer.lookup_transform(
self.global_frame,
self.base_frame,
rclpy.time.Time(),
timeout=Duration(seconds=0.3),
)
except TransformException as exc:
self.get_logger().warn(f'TF lookup failed: {exc}')
return None
translation = trans.transform.translation
rotation = trans.transform.rotation
return (
translation.x,
translation.y,
self._yaw_from_quaternion(rotation.x, rotation.y, rotation.z, rotation.w),
)
def _calculate_error(self, pose, target):
x, y, yaw = pose
target_x, target_y, target_yaw = target
distance = math.hypot(target_x - x, target_y - y)
yaw_error = self._normalize_angle(target_yaw - yaw)
return distance, yaw_error
def _log_progress(self, pose, distance, yaw_error, elapsed, cmd):
now = self.get_clock().now()
if (now - self.last_log_time).nanoseconds < 1e9:
return
self.get_logger().info(
f'[FINAL YAW REFINE RUNNING] '
f'distance={distance:.3f} m, yaw_error={math.degrees(yaw_error):+.2f} deg, '
f'elapsed={elapsed:.1f} s, cmd_wz={cmd.angular.z:+.3f}, '
f'pose=({pose[0]:.3f}, {pose[1]:.3f}, {math.degrees(pose[2]):.1f} deg)'
)
self.last_log_time = now
def _publish_status(self, status):
msg = String()
msg.data = status
self.status_pub.publish(msg)
def _publish_stop(self):
try:
self.cmd_vel_pub.publish(Twist())
except Exception:
pass
def _stop_robot(self):
for _ in range(5):
self._publish_stop()
def _stop_robot_with_ros_cli(self):
topic = shlex.quote(self.cmd_vel_topic)
zero_twist = (
'"{linear: {x: 0.0, y: 0.0, z: 0.0}, '
'angular: {x: 0.0, y: 0.0, z: 0.0}}"'
)
os.system(
f'timeout 2s ros2 topic pub --once {topic} '
f'geometry_msgs/msg/Twist {zero_twist} >/dev/null 2>&1'
)
def _reset_start_refine(self):
self.set_parameters([
Parameter(self.start_param, Parameter.Type.BOOL, False),
])
def _reset_cancel_refine(self):
self.set_parameters([
Parameter(self.cancel_param, Parameter.Type.BOOL, False),
])
@staticmethod
def _clip(value, low, high):
return max(low, min(high, value))
@staticmethod
def _apply_min_abs(value, min_abs):
min_abs = max(abs(min_abs), 0.0)
if value == 0.0 or abs(value) >= min_abs:
return value
return math.copysign(min_abs, value)
@staticmethod
def _normalize_angle(angle):
return math.atan2(math.sin(angle), math.cos(angle))
@staticmethod
def _yaw_from_quaternion(x, y, z, w):
siny_cosp = 2.0 * (w * z + x * y)
cosy_cosp = 1.0 - 2.0 * (y * y + z * z)
return math.atan2(siny_cosp, cosy_cosp)
def main(args=None):
rclpy.init(args=args)
node = FinalPoseRefiner()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node._stop_robot()
node._stop_robot_with_ros_cli()
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,397 @@
#!/usr/bin/env python3
"""Transparent final-refinement proxy for Nav2 pose navigation actions."""
import threading
import time
from copy import deepcopy
import rclpy
from action_msgs.msg import GoalStatus
from geometry_msgs.msg import PoseStamped
from nav2_msgs.action import NavigateThroughPoses, NavigateToPose
from rcl_interfaces.msg import Parameter as ParameterMsg
from rcl_interfaces.msg import ParameterType, ParameterValue
from rcl_interfaces.srv import SetParameters
from rclpy.action import ActionClient, ActionServer, CancelResponse, GoalResponse
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from std_msgs.msg import String
class NavigateToPoseRefinerProxy(Node):
"""Forward pose-navigation actions and complete them after final yaw refinement."""
TERMINAL_REFINER_STATUSES = {
'succeeded',
'timeout',
'failed_tf',
'no_goal',
'handoff_distance_exceeded',
'canceled',
}
STARTLESS_REFINER_FAILURES = {
'failed_tf',
'no_goal',
'handoff_distance_exceeded',
}
def __init__(self):
super().__init__('navigate_to_pose_refiner_proxy')
self.public_goal_topic = '/goal_pose'
self.refiner_goal_topic = '/final_pose_refiner/goal_pose'
self.refiner_status_topic = '/final_pose_refiner/status'
self.refiner_param_service = '/final_pose_refiner/set_parameters'
self.start_param = 'final_pose_refiner_start'
self.cancel_param = 'final_pose_refiner_cancel'
self.declare_parameter('nav2_server_timeout_sec', 5.0)
self.declare_parameter('refiner_service_timeout_sec', 2.0)
self.declare_parameter('refiner_wait_timeout_sec', 25.0)
self.declare_parameter('require_refinement', True)
self.declare_parameter('debug_print', False)
self.callback_group = ReentrantCallbackGroup()
self.goal_pub = self.create_publisher(PoseStamped, self.refiner_goal_topic, 10)
self.refiner_status_sub = self.create_subscription(
String,
self.refiner_status_topic,
self._on_refiner_status,
10,
callback_group=self.callback_group,
)
self.refiner_param_client = self.create_client(
SetParameters,
self.refiner_param_service,
callback_group=self.callback_group,
)
self._refinement_lock = threading.Lock()
self._status_condition = threading.Condition()
self._status_sequence = 0
self._status_history = []
self.routes = []
self._add_route(
'NavigateToPose',
NavigateToPose,
'/navigate_to_pose',
'/navigate_to_pose_nav2',
lambda request: request.pose,
)
self._add_route(
'NavigateThroughPoses',
NavigateThroughPoses,
'/navigate_through_poses',
'/navigate_through_poses_nav2',
lambda request: request.poses[-1] if request.poses else None,
)
self.topic_nav_client = ActionClient(
self,
NavigateToPose,
'/navigate_to_pose',
callback_group=self.callback_group,
)
self.goal_topic_sub = self.create_subscription(
PoseStamped,
self.public_goal_topic,
self._on_goal_pose,
10,
callback_group=self.callback_group,
)
self.get_logger().info(
'Navigation refinement proxy ready for NavigateToPose, NavigateThroughPoses, '
'and /goal_pose; public tasks complete after final yaw refinement.'
)
def _add_route(self, label, action_type, public_name, nav2_name, final_pose_getter):
route = {
'label': label,
'action_type': action_type,
'public_name': public_name,
'nav2_name': nav2_name,
'final_pose_getter': final_pose_getter,
}
route['client'] = ActionClient(
self,
action_type,
nav2_name,
callback_group=self.callback_group,
)
route['server'] = ActionServer(
self,
action_type,
public_name,
execute_callback=lambda handle, current=route: self._execute_callback(current, handle),
goal_callback=lambda request, current=route: self._goal_callback(current, request),
cancel_callback=self._cancel_callback,
callback_group=self.callback_group,
)
self.routes.append(route)
self._debug(f'{label} route: {public_name} -> {nav2_name}')
def _goal_callback(self, route, goal_request):
if not route['client'].server_is_ready():
self.get_logger().warn(
f"{route['label']} Nav2 action server {route['nav2_name']} is not ready; "
'rejecting goal.'
)
return GoalResponse.REJECT
final_pose = route['final_pose_getter'](goal_request)
if final_pose is not None:
self._publish_refiner_goal(final_pose)
return GoalResponse.ACCEPT
@staticmethod
def _cancel_callback(_goal_handle):
return CancelResponse.ACCEPT
def _on_goal_pose(self, pose):
goal = NavigateToPose.Goal()
goal.pose = deepcopy(pose)
if not self.topic_nav_client.server_is_ready():
self.get_logger().error(
'Cannot forward /goal_pose: public NavigateToPose is unavailable.'
)
return
send_future = self.topic_nav_client.send_goal_async(goal)
send_future.add_done_callback(self._on_topic_goal_response)
def _on_topic_goal_response(self, future):
try:
goal_handle = future.result()
except Exception as exc:
self.get_logger().error(f'Failed to forward /goal_pose to NavigateToPose: {exc}')
return
if goal_handle is None or not goal_handle.accepted:
self.get_logger().error('/goal_pose navigation goal was rejected.')
return
result_future = goal_handle.get_result_async()
result_future.add_done_callback(self._on_topic_goal_result)
def _on_topic_goal_result(self, future):
try:
action_result = future.result()
except Exception as exc:
self.get_logger().error(f'Failed to receive /goal_pose navigation result: {exc}')
return
if action_result.status != GoalStatus.STATUS_SUCCEEDED:
self.get_logger().warn(
f'/goal_pose navigation ended with action status {action_result.status}.'
)
def _execute_callback(self, route, goal_handle):
nav_result = self._forward_to_nav2(route, goal_handle)
if nav_result is None:
return route['action_type'].Result()
result, status = nav_result
if status == GoalStatus.STATUS_CANCELED:
goal_handle.canceled()
return result
if status != GoalStatus.STATUS_SUCCEEDED:
goal_handle.abort()
return result
final_pose = route['final_pose_getter'](goal_handle.request)
refine_status = 'succeeded'
if final_pose is not None:
refine_status = self._refine_final_pose(goal_handle, final_pose)
if refine_status == 'succeeded':
goal_handle.succeed()
elif refine_status == 'canceled':
goal_handle.canceled()
else:
self.get_logger().error(
f"{route['label']} completed in Nav2 but final refinement ended with "
f"status '{refine_status}'."
)
goal_handle.abort()
return result
def _forward_to_nav2(self, route, goal_handle):
timeout = float(self.get_parameter('nav2_server_timeout_sec').value)
if not route['client'].wait_for_server(timeout_sec=timeout):
self.get_logger().error(f"Nav2 action server {route['nav2_name']} is not available.")
goal_handle.abort()
return None
send_future = route['client'].send_goal_async(
deepcopy(goal_handle.request),
feedback_callback=lambda message: self._relay_feedback(goal_handle, message),
)
if not self._wait_for_future(send_future, timeout):
self.get_logger().error(f"Timed out forwarding {route['label']} goal to Nav2.")
goal_handle.abort()
return None
try:
nav_goal_handle = send_future.result()
except Exception as exc:
self.get_logger().error(f"Failed to forward {route['label']} goal to Nav2: {exc}")
goal_handle.abort()
return None
if nav_goal_handle is None or not nav_goal_handle.accepted:
self.get_logger().error(f"Forwarded {route['label']} goal was rejected by Nav2.")
goal_handle.abort()
return None
result_future = nav_goal_handle.get_result_async()
while rclpy.ok() and not result_future.done():
if goal_handle.is_cancel_requested:
self._cancel_nav_goal(nav_goal_handle)
goal_handle.canceled()
return None
time.sleep(0.05)
if not result_future.done():
goal_handle.abort()
return None
try:
nav_result = result_future.result()
except Exception as exc:
self.get_logger().error(f"Failed to get Nav2 {route['label']} result: {exc}")
goal_handle.abort()
return None
result = (
nav_result.result
if nav_result and nav_result.result
else route['action_type'].Result()
)
return result, nav_result.status
def _refine_final_pose(self, goal_handle, pose):
if not self.get_parameter('require_refinement').value:
return 'succeeded'
with self._refinement_lock:
if goal_handle.is_cancel_requested:
return 'canceled'
self._publish_refiner_goal(pose)
start_sequence = self._status_snapshot()
if not self._set_refiner_parameter(self.start_param, True):
return 'unavailable'
wait_timeout = float(self.get_parameter('refiner_wait_timeout_sec').value)
deadline = time.monotonic() + max(wait_timeout, 0.0)
saw_running = False
sequence = start_sequence
while rclpy.ok():
if goal_handle.is_cancel_requested:
self._set_refiner_parameter(self.cancel_param, True)
return 'canceled'
updates = self._wait_for_status_updates(sequence, deadline)
if updates is None:
self.get_logger().error('Timed out waiting for final pose refinement result.')
self._set_refiner_parameter(self.cancel_param, True)
return 'timeout'
for sequence, status in updates:
if status == 'running':
saw_running = True
elif status in self.TERMINAL_REFINER_STATUSES:
if saw_running or status in self.STARTLESS_REFINER_FAILURES:
return status
return 'canceled'
def _set_refiner_parameter(self, name, value):
timeout = float(self.get_parameter('refiner_service_timeout_sec').value)
if not self.refiner_param_client.wait_for_service(timeout_sec=timeout):
self.get_logger().error(
f'Final pose refiner parameter service {self.refiner_param_service} '
'is unavailable.'
)
return False
parameter = ParameterMsg()
parameter.name = name
parameter.value = ParameterValue(type=ParameterType.PARAMETER_BOOL, bool_value=value)
request = SetParameters.Request()
request.parameters = [parameter]
future = self.refiner_param_client.call_async(request)
if not self._wait_for_future(future, timeout):
self.get_logger().error(f'Timed out setting final pose refiner parameter {name}.')
return False
response = future.result()
if response is None or not response.results or not response.results[0].successful:
reason = response.results[0].reason if response and response.results else ''
self.get_logger().error(f'Failed to set final pose refiner parameter {name}: {reason}')
return False
return True
def _on_refiner_status(self, message):
with self._status_condition:
self._status_sequence += 1
self._status_history.append((self._status_sequence, message.data))
self._status_history = self._status_history[-32:]
self._status_condition.notify_all()
def _status_snapshot(self):
with self._status_condition:
return self._status_sequence
def _wait_for_status_updates(self, sequence, deadline):
with self._status_condition:
while rclpy.ok():
updates = [item for item in self._status_history if item[0] > sequence]
if updates:
return updates
remaining = deadline - time.monotonic()
if remaining <= 0.0:
return None
self._status_condition.wait(timeout=min(remaining, 0.1))
return None
def _publish_refiner_goal(self, pose):
refiner_goal = deepcopy(pose)
refiner_goal.header.stamp = self.get_clock().now().to_msg()
self.goal_pub.publish(refiner_goal)
@staticmethod
def _relay_feedback(goal_handle, feedback_message):
if goal_handle.is_active:
goal_handle.publish_feedback(feedback_message.feedback)
def _debug(self, message):
if self.get_parameter('debug_print').value:
self.get_logger().info(message)
@staticmethod
def _wait_for_future(future, timeout_sec):
done = threading.Event()
future.add_done_callback(lambda _: done.set())
return done.wait(timeout_sec)
def _cancel_nav_goal(self, nav_goal_handle):
cancel_future = nav_goal_handle.cancel_goal_async()
self._wait_for_future(cancel_future, 2.0)
def main(args=None):
rclpy.init(args=args)
node = NavigateToPoseRefinerProxy()
executor = MultiThreadedExecutor(num_threads=6)
try:
rclpy.spin(node, executor=executor)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,469 @@
#!/usr/bin/env python3
"""X-axis odometry scale calibration helper for AGV Pro."""
import math
import os
import shlex
import statistics
import sys
import threading
import rclpy
from geometry_msgs.msg import Twist
from rclpy.duration import Duration
from rclpy.node import Node
from rclpy.parameter import Parameter
from tf2_ros import Buffer, TransformException, TransformListener
CONTROL_RATE_HZ = 20.0
MAX_SPEED_LIMIT = 0.30
TF_TIMEOUT_SEC = 0.5
STOP_REPEAT_COUNT = 5
class OdomLinearCalib(Node):
"""Run repeated X-axis odom tests and compute the final scale from cached samples."""
def __init__(self):
super().__init__('odom_linear_calib')
self.declare_parameter('cmd_vel_topic', '/cmd_vel')
self.declare_parameter('odom_frame', 'odom')
self.declare_parameter('base_frame', 'base_footprint')
self.declare_parameter('start_test', False)
self.declare_parameter('test_distance', 1.0)
self.declare_parameter('speed', 0.10)
self.declare_parameter('tolerance', 0.01)
self.declare_parameter('odom_linear_scale_correction', 1.0)
self.declare_parameter('timeout', 30.0)
self.cmd_vel_topic = self.get_parameter('cmd_vel_topic').value
self.cmd_vel_pub = self.create_publisher(Twist, self.cmd_vel_topic, 10)
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.state = 'idle'
self.start_pose = None
self.direction_sign = 1.0
self.signed_target_distance = 1.0
self.target_distance = 1.0
self.command_speed = 0.10
self.tolerance = 0.01
self.odom_linear_scale_correction = 1.0
self.timeout = 30.0
self.start_time = None
self.last_odom_distance = 0.0
self.last_log_time = self.get_clock().now()
self.samples = []
self.samples_lock = threading.Lock()
self.pending_sample = None
self.timer = self.create_timer(1.0 / CONTROL_RATE_HZ, self.on_timer)
threading.Thread(target=self._stdin_loop, daemon=True).start()
self.get_logger().info(
'odom_linear_calib ready. Set params, set start_test:=true for each run, '
'use positive test_distance for forward and negative for backward, '
'then enter the measured ground error in cm after the robot stops. '
'Enter 0 to finish and print the cached scale summary; enter any text to skip a verification run.'
)
def _stdin_loop(self):
while True:
line = sys.stdin.readline()
if line == '':
return
self._handle_input_line(line.strip())
def _handle_input_line(self, text):
if not text:
self.get_logger().info(
'Input ignored. After a successful run enter ground error in cm '
'(+over target along motion direction, -short), or enter 0 to finish.'
)
return
try:
value = float(text)
except ValueError:
self._skip_pending_sample(text)
return
if value == 0.0 and not text.startswith(('+', '-')):
with self.samples_lock:
had_pending_sample = self.pending_sample is not None
self.pending_sample = None
if self.state == 'awaiting_input':
self.state = 'idle'
if had_pending_sample:
self.get_logger().warn('Pending run was not recorded because finish input 0 was entered.')
self._print_summary()
return
self._record_pending_sample(value)
def on_timer(self):
if self.state == 'running':
self._run_test_step()
return
if self.state == 'awaiting_input':
if self.get_parameter('start_test').value:
self.get_logger().warn(
'A finished run is waiting for ground-error input; record it before starting again.'
)
self._reset_start_test()
return
if self.get_parameter('start_test').value:
self._start_test()
def _start_test(self):
config = self._read_test_config()
if config is None:
self._reset_start_test()
return
pose = self._lookup_pose()
if pose is None:
self.get_logger().warn('Cannot start test: odom transform is not available.')
self._reset_start_test()
return
self.signed_target_distance = config['signed_test_distance']
self.target_distance = config['target_distance']
self.command_speed = config['speed']
self.tolerance = config['tolerance']
self.odom_linear_scale_correction = config['odom_linear_scale_correction']
self.timeout = config['timeout']
self.direction_sign = float(config['direction_sign'])
self.start_pose = pose
self.start_time = self.get_clock().now()
self.last_odom_distance = 0.0
self.state = 'running'
self.get_logger().info(
f'Start X odom calibration: direction={int(self.direction_sign)}, '
f'signed_target={self.signed_target_distance:.3f} m, '
f'target={self.target_distance:.3f} m, speed={self.command_speed:.3f} m/s, '
f'odom_linear_scale_correction={self.odom_linear_scale_correction:.6f}'
)
def _run_test_step(self):
pose = self._lookup_pose()
if pose is None:
self._finish_test('failed_tf', publish_warning=True)
return
raw_progress, lateral_drift = self._calculate_progress(pose)
corrected_progress = raw_progress * self.odom_linear_scale_correction
error = corrected_progress - self.target_distance
elapsed = (self.get_clock().now() - self.start_time).nanoseconds / 1e9
self.last_odom_distance = raw_progress
if corrected_progress >= self.target_distance - self.tolerance:
self._finish_test('succeeded', raw_progress, corrected_progress, lateral_drift, elapsed)
return
if elapsed > self.timeout:
self._finish_test('timeout', raw_progress, corrected_progress, lateral_drift, elapsed)
return
cmd = Twist()
cmd.linear.x = self.direction_sign * self.command_speed
self.cmd_vel_pub.publish(cmd)
self._log_progress(raw_progress, corrected_progress, error, lateral_drift, elapsed)
def _finish_test(
self,
status,
odom_distance=None,
corrected_distance=None,
lateral_drift=None,
elapsed=None,
publish_warning=False,
):
self._stop_robot()
self._reset_start_test()
if odom_distance is None:
odom_distance = self.last_odom_distance
if corrected_distance is None:
corrected_distance = odom_distance * self.odom_linear_scale_correction
if lateral_drift is None:
lateral_drift = 0.0
if elapsed is None and self.start_time is not None:
elapsed = (self.get_clock().now() - self.start_time).nanoseconds / 1e9
if elapsed is None:
elapsed = 0.0
if status == 'succeeded' and odom_distance > 0.0:
pending_sample = {
'direction': int(self.direction_sign),
'signed_target_distance': self.signed_target_distance,
'target_distance': self.target_distance,
'odom_distance': odom_distance,
'corrected_distance': corrected_distance,
'lateral_drift': lateral_drift,
'elapsed': elapsed,
'used_correction': self.odom_linear_scale_correction,
}
with self.samples_lock:
self.pending_sample = pending_sample
self.state = 'awaiting_input'
self.get_logger().info(
'Run is waiting for measured ground error. '
'Enter cm error now: +over target along motion direction, -short of target, '
'+0/-0 for exact target, 0 to finish, or any text to skip this run.'
)
else:
self.state = 'idle'
msg = (
f'Calibration {status}: odom_distance={odom_distance:.4f} m, '
f'corrected_distance={corrected_distance:.4f} m, '
f'lateral_drift={lateral_drift:.4f} m, elapsed={elapsed:.2f} s, '
f'target={self.target_distance:.4f} m, '
f'used_correction={self.odom_linear_scale_correction:.6f}.'
)
if publish_warning:
self.get_logger().warn(msg)
else:
self.get_logger().info(msg)
def _read_test_config(self):
test_distance = self.get_parameter('test_distance').value
speed = abs(self.get_parameter('speed').value)
tolerance = max(self.get_parameter('tolerance').value, 0.0)
correction = self.get_parameter('odom_linear_scale_correction').value
timeout = self.get_parameter('timeout').value
if test_distance == 0.0:
self.get_logger().error(
'test_distance must not be 0.0 m. Use a positive value for forward, negative for backward.'
)
return None
if speed <= 0.0:
self.get_logger().error('speed must be greater than 0.0 m/s.')
return None
if timeout <= 0.0:
self.get_logger().error('timeout must be greater than 0.0 s.')
return None
if correction <= 0.0:
self.get_logger().error('odom_linear_scale_correction must be greater than 0.0.')
return None
if speed > MAX_SPEED_LIMIT:
self.get_logger().warn(
f'speed {speed:.3f} m/s exceeds internal safety limit '
f'{MAX_SPEED_LIMIT:.3f} m/s; clipping command speed.'
)
speed = MAX_SPEED_LIMIT
direction_sign = 1 if test_distance > 0.0 else -1
return {
'direction_sign': direction_sign,
'signed_test_distance': test_distance,
'target_distance': abs(test_distance),
'speed': speed,
'tolerance': tolerance,
'odom_linear_scale_correction': correction,
'timeout': timeout,
}
def _lookup_pose(self):
odom_frame = self.get_parameter('odom_frame').value
base_frame = self.get_parameter('base_frame').value
try:
trans = self.tf_buffer.lookup_transform(
odom_frame,
base_frame,
rclpy.time.Time(),
timeout=Duration(seconds=TF_TIMEOUT_SEC),
)
except TransformException as exc:
self.get_logger().warn(f'TF lookup failed: {exc}')
return None
translation = trans.transform.translation
rotation = trans.transform.rotation
return (
translation.x,
translation.y,
self._yaw_from_quaternion(rotation.x, rotation.y, rotation.z, rotation.w),
)
def _calculate_progress(self, pose):
x, y, _ = pose
start_x, start_y, start_yaw = self.start_pose
dx = x - start_x
dy = y - start_y
cos_yaw = math.cos(start_yaw)
sin_yaw = math.sin(start_yaw)
forward_delta = dx * cos_yaw + dy * sin_yaw
lateral_drift = -dx * sin_yaw + dy * cos_yaw
progress = self.direction_sign * forward_delta
return progress, lateral_drift
def _log_progress(self, raw_progress, corrected_progress, error, lateral_drift, elapsed):
now = self.get_clock().now()
if (now - self.last_log_time).nanoseconds < 1e9:
return
self.get_logger().info(
f'odom_distance={raw_progress:.3f} m, '
f'corrected_distance={corrected_progress:.3f} m, '
f'error={error:+.3f} m, lateral_drift={lateral_drift:.3f} m, '
f'elapsed={elapsed:.1f} s'
)
self.last_log_time = now
def _skip_pending_sample(self, reason):
with self.samples_lock:
if self.pending_sample is None:
self.get_logger().warn(
f'Input "{reason}" ignored. No pending successful run is waiting for input.'
)
return
skipped_sample = self.pending_sample
self.pending_sample = None
self.state = 'idle'
self.get_logger().info(
f'Skipped pending run by input "{reason}": '
f'direction={skipped_sample["direction"]:+d}, '
f'signed_target={skipped_sample["signed_target_distance"]:.4f} m, '
f'odom={skipped_sample["odom_distance"]:.4f} m, '
f'corrected={skipped_sample["corrected_distance"]:.4f} m, '
f'used_correction={skipped_sample["used_correction"]:.6f}. '
'This run will not be used in the final scale summary.'
)
def _record_pending_sample(self, ground_error_cm):
with self.samples_lock:
if self.pending_sample is None:
self.get_logger().warn(
'No pending successful run. Set start_test:=true first, wait for the robot to stop, '
'then enter the measured cm error.'
)
return
actual_distance = self.pending_sample['target_distance'] + ground_error_cm / 100.0
if actual_distance <= 0.0:
self.get_logger().error(
f'Invalid measured result: target + error = {actual_distance:.4f} m. '
'Re-enter the cm error for this pending run.'
)
return
sample = dict(self.pending_sample)
sample['ground_error_cm'] = ground_error_cm
sample['actual_distance'] = actual_distance
sample['scale'] = actual_distance / sample['odom_distance']
self.samples.append(sample)
sample_index = len(self.samples)
direction_index = sum(
1 for recorded_sample in self.samples
if recorded_sample['direction'] == sample['direction']
)
self.pending_sample = None
self.state = 'idle'
self.get_logger().info(
f'Recorded sample #{sample_index} overall, direction {sample["direction"]:+d} #{direction_index}: '
f'actual={actual_distance:.4f} m, '
f'ground_error={ground_error_cm:+.2f} cm, odom={sample["odom_distance"]:.4f} m, '
f'scale={sample["scale"]:.6f}. Set start_test:=true for the next run, or enter 0 to finish.'
)
def _print_summary(self):
with self.samples_lock:
samples = list(self.samples)
if not samples:
self.get_logger().warn('No successful calibration samples have been recorded yet.')
return
self.get_logger().info('========== X ODOM SCALE SUMMARY ==========')
for index, sample in enumerate(samples, start=1):
self.get_logger().info(
f'#{index:02d} direction={sample["direction"]:+d}, '
f'signed_target={sample["signed_target_distance"]:.4f} m, '
f'target={sample["target_distance"]:.4f} m, '
f'actual={sample["actual_distance"]:.4f} m, '
f'ground_error={sample["ground_error_cm"]:+.2f} cm, '
f'odom={sample["odom_distance"]:.4f} m, '
f'corrected={sample["corrected_distance"]:.4f} m, '
f'lateral_drift={sample["lateral_drift"]:.4f} m, '
f'used_correction={sample["used_correction"]:.6f}, '
f'scale={sample["scale"]:.6f}'
)
self._print_scale_stats('all', samples)
for direction in (1, -1):
direction_samples = [sample for sample in samples if sample['direction'] == direction]
if direction_samples:
self._print_scale_stats(f'direction={direction:+d}', direction_samples)
self.get_logger().info('Restart this node to clear cached samples.')
def _print_scale_stats(self, label, samples):
scales = [sample['scale'] for sample in samples]
mean_scale = statistics.fmean(scales)
std_scale = statistics.pstdev(scales) if len(scales) > 1 else 0.0
self.get_logger().info(
f'{label}: samples={len(scales)}, recommended_odometry.scale_x={mean_scale:.6f}, '
f'std={std_scale:.6f}, min={min(scales):.6f}, max={max(scales):.6f}'
)
def _publish_stop(self):
try:
self.cmd_vel_pub.publish(Twist())
except Exception:
pass
def _stop_robot(self):
for _ in range(STOP_REPEAT_COUNT):
self._publish_stop()
def _stop_robot_with_ros_cli(self):
topic = shlex.quote(self.cmd_vel_topic)
zero_twist = (
'"{linear: {x: 0.0, y: 0.0, z: 0.0}, '
'angular: {x: 0.0, y: 0.0, z: 0.0}}"'
)
os.system(
f'timeout 2s ros2 topic pub --once {topic} '
f'geometry_msgs/msg/Twist {zero_twist} >/dev/null 2>&1'
)
def _reset_start_test(self):
self.set_parameters([
Parameter('start_test', Parameter.Type.BOOL, False),
])
@staticmethod
def _yaw_from_quaternion(x, y, z, w):
siny_cosp = 2.0 * (w * z + x * y)
cosy_cosp = 1.0 - 2.0 * (y * y + z * z)
return math.atan2(siny_cosp, cosy_cosp)
def main(args=None):
rclpy.init(args=args)
node = OdomLinearCalib()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node._stop_robot()
node._stop_robot_with_ros_cli()
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,466 @@
#!/usr/bin/env python3
"""Yaw odometry scale calibration helper for AGV Pro."""
import math
import os
import shlex
import statistics
import sys
import threading
import rclpy
from geometry_msgs.msg import Twist
from rclpy.duration import Duration
from rclpy.node import Node
from rclpy.parameter import Parameter
from tf2_ros import Buffer, TransformException, TransformListener
CONTROL_RATE_HZ = 20.0
MAX_ANGULAR_SPEED_LIMIT = 0.50
TF_TIMEOUT_SEC = 0.5
STOP_REPEAT_COUNT = 5
class OdomYawCalib(Node):
"""Run repeated yaw odom tests and compute the final scale from cached samples."""
def __init__(self):
super().__init__('odom_yaw_calib')
self.declare_parameter('cmd_vel_topic', '/cmd_vel')
self.declare_parameter('odom_frame', 'odom')
self.declare_parameter('base_frame', 'base_footprint')
self.declare_parameter('start_test', False)
self.declare_parameter('test_angle', 360.0)
self.declare_parameter('speed', 0.20)
self.declare_parameter('tolerance', 2.0)
self.declare_parameter('odom_yaw_scale_correction', 1.0)
self.declare_parameter('timeout', 60.0)
self.cmd_vel_topic = self.get_parameter('cmd_vel_topic').value
self.cmd_vel_pub = self.create_publisher(Twist, self.cmd_vel_topic, 10)
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.state = 'idle'
self.direction_sign = 1.0
self.signed_target_angle_deg = 360.0
self.target_angle_deg = 360.0
self.target_angle = math.radians(360.0)
self.command_speed = 0.20
self.tolerance_deg = 2.0
self.tolerance = math.radians(2.0)
self.odom_yaw_scale_correction = 1.0
self.timeout = 60.0
self.start_time = None
self.prev_yaw = None
self.accumulated_yaw = 0.0
self.last_odom_angle = 0.0
self.last_log_time = self.get_clock().now()
self.samples = []
self.samples_lock = threading.Lock()
self.pending_sample = None
self.timer = self.create_timer(1.0 / CONTROL_RATE_HZ, self.on_timer)
threading.Thread(target=self._stdin_loop, daemon=True).start()
self.get_logger().info(
'odom_yaw_calib ready. Set params, set start_test:=true for each run, '
'use positive test_angle for positive angular.z and negative for negative angular.z, '
'then enter the measured ground yaw error in deg after the robot stops. '
'Enter 0 to finish and print the cached scale summary; enter any text to skip a verification run.'
)
def _stdin_loop(self):
while True:
line = sys.stdin.readline()
if line == '':
return
self._handle_input_line(line.strip())
def _handle_input_line(self, text):
if not text:
self.get_logger().info(
'Input ignored. After a successful run enter ground yaw error in deg '
'(+over target along rotation direction, -short), or enter 0 to finish.'
)
return
try:
value = float(text)
except ValueError:
self._skip_pending_sample(text)
return
if value == 0.0 and not text.startswith(('+', '-')):
with self.samples_lock:
had_pending_sample = self.pending_sample is not None
self.pending_sample = None
if self.state == 'awaiting_input':
self.state = 'idle'
if had_pending_sample:
self.get_logger().warn('Pending run was not recorded because finish input 0 was entered.')
self._print_summary()
return
self._record_pending_sample(value)
def on_timer(self):
if self.state == 'running':
self._run_test_step()
return
if self.state == 'awaiting_input':
if self.get_parameter('start_test').value:
self.get_logger().warn(
'A finished run is waiting for ground-yaw-error input; record it before starting again.'
)
self._reset_start_test()
return
if self.get_parameter('start_test').value:
self._start_test()
def _start_test(self):
config = self._read_test_config()
if config is None:
self._reset_start_test()
return
pose = self._lookup_pose()
if pose is None:
self.get_logger().warn('Cannot start test: odom transform is not available.')
self._reset_start_test()
return
self.signed_target_angle_deg = config['signed_test_angle']
self.target_angle_deg = config['target_angle']
self.target_angle = math.radians(config['target_angle'])
self.command_speed = config['speed']
self.tolerance_deg = config['tolerance']
self.tolerance = math.radians(config['tolerance'])
self.odom_yaw_scale_correction = config['odom_yaw_scale_correction']
self.timeout = config['timeout']
self.direction_sign = float(config['direction_sign'])
self.prev_yaw = pose[2]
self.accumulated_yaw = 0.0
self.start_time = self.get_clock().now()
self.last_odom_angle = 0.0
self.state = 'running'
self.get_logger().info(
f'Start yaw odom calibration: direction={int(self.direction_sign)}, '
f'signed_target={self.signed_target_angle_deg:.1f} deg, '
f'target={self.target_angle_deg:.1f} deg, speed={self.command_speed:.3f} rad/s, '
f'odom_yaw_scale_correction={self.odom_yaw_scale_correction:.6f}'
)
def _run_test_step(self):
pose = self._lookup_pose()
if pose is None:
self._finish_test('failed_tf', publish_warning=True)
return
raw_progress = self._calculate_yaw_progress(pose)
raw_angle = max(raw_progress, 0.0)
corrected_angle = raw_angle * self.odom_yaw_scale_correction
error = corrected_angle - self.target_angle
elapsed = (self.get_clock().now() - self.start_time).nanoseconds / 1e9
self.last_odom_angle = raw_angle
if corrected_angle >= self.target_angle - self.tolerance:
self._finish_test('succeeded', raw_angle, corrected_angle, elapsed)
return
if elapsed > self.timeout:
self._finish_test('timeout', raw_angle, corrected_angle, elapsed)
return
cmd = Twist()
cmd.angular.z = self.direction_sign * self.command_speed
self.cmd_vel_pub.publish(cmd)
self._log_progress(raw_angle, corrected_angle, error, elapsed)
def _finish_test(
self,
status,
odom_angle=None,
corrected_angle=None,
elapsed=None,
publish_warning=False,
):
self._stop_robot()
self._reset_start_test()
if odom_angle is None:
odom_angle = self.last_odom_angle
if corrected_angle is None:
corrected_angle = odom_angle * self.odom_yaw_scale_correction
if elapsed is None and self.start_time is not None:
elapsed = (self.get_clock().now() - self.start_time).nanoseconds / 1e9
if elapsed is None:
elapsed = 0.0
if status == 'succeeded' and odom_angle > 0.0:
pending_sample = {
'direction': int(self.direction_sign),
'signed_target_angle_deg': self.signed_target_angle_deg,
'target_angle_deg': self.target_angle_deg,
'odom_angle_deg': math.degrees(odom_angle),
'corrected_angle_deg': math.degrees(corrected_angle),
'elapsed': elapsed,
'used_correction': self.odom_yaw_scale_correction,
}
with self.samples_lock:
self.pending_sample = pending_sample
self.state = 'awaiting_input'
self.get_logger().info(
'Run is waiting for measured ground yaw error. '
'Enter deg error now: +over target along rotation direction, -short of target, '
'+0/-0 for exact target, 0 to finish, or any text to skip this run.'
)
else:
self.state = 'idle'
msg = (
f'Calibration {status}: odom_angle={math.degrees(odom_angle):.2f} deg, '
f'corrected_angle={math.degrees(corrected_angle):.2f} deg, '
f'elapsed={elapsed:.2f} s, target={self.target_angle_deg:.2f} deg, '
f'used_correction={self.odom_yaw_scale_correction:.6f}.'
)
if publish_warning:
self.get_logger().warn(msg)
else:
self.get_logger().info(msg)
def _read_test_config(self):
test_angle = self.get_parameter('test_angle').value
speed = abs(self.get_parameter('speed').value)
tolerance = max(self.get_parameter('tolerance').value, 0.0)
correction = self.get_parameter('odom_yaw_scale_correction').value
timeout = self.get_parameter('timeout').value
if test_angle == 0.0:
self.get_logger().error(
'test_angle must not be 0.0 deg. Use a positive value for one yaw direction, '
'negative for the opposite direction.'
)
return None
if speed <= 0.0:
self.get_logger().error('speed must be greater than 0.0 rad/s.')
return None
if timeout <= 0.0:
self.get_logger().error('timeout must be greater than 0.0 s.')
return None
if correction <= 0.0:
self.get_logger().error('odom_yaw_scale_correction must be greater than 0.0.')
return None
if speed > MAX_ANGULAR_SPEED_LIMIT:
self.get_logger().warn(
f'speed {speed:.3f} rad/s exceeds internal safety limit '
f'{MAX_ANGULAR_SPEED_LIMIT:.3f} rad/s; clipping command speed.'
)
speed = MAX_ANGULAR_SPEED_LIMIT
direction_sign = 1 if test_angle > 0.0 else -1
return {
'direction_sign': direction_sign,
'signed_test_angle': test_angle,
'target_angle': abs(test_angle),
'speed': speed,
'tolerance': tolerance,
'odom_yaw_scale_correction': correction,
'timeout': timeout,
}
def _lookup_pose(self):
odom_frame = self.get_parameter('odom_frame').value
base_frame = self.get_parameter('base_frame').value
try:
trans = self.tf_buffer.lookup_transform(
odom_frame,
base_frame,
rclpy.time.Time(),
timeout=Duration(seconds=TF_TIMEOUT_SEC),
)
except TransformException as exc:
self.get_logger().warn(f'TF lookup failed: {exc}')
return None
rotation = trans.transform.rotation
return (
trans.transform.translation.x,
trans.transform.translation.y,
self._yaw_from_quaternion(rotation.x, rotation.y, rotation.z, rotation.w),
)
def _calculate_yaw_progress(self, pose):
current_yaw = pose[2]
delta = math.atan2(
math.sin(current_yaw - self.prev_yaw),
math.cos(current_yaw - self.prev_yaw),
)
self.accumulated_yaw += delta
self.prev_yaw = current_yaw
return self.direction_sign * self.accumulated_yaw
def _log_progress(self, raw_angle, corrected_angle, error, elapsed):
now = self.get_clock().now()
if (now - self.last_log_time).nanoseconds < 1e9:
return
self.get_logger().info(
f'odom_angle={math.degrees(raw_angle):.1f} deg, '
f'corrected_angle={math.degrees(corrected_angle):.1f} deg, '
f'error={math.degrees(error):+.1f} deg, elapsed={elapsed:.1f} s'
)
self.last_log_time = now
def _skip_pending_sample(self, reason):
with self.samples_lock:
if self.pending_sample is None:
self.get_logger().warn(
f'Input "{reason}" ignored. No pending successful run is waiting for input.'
)
return
skipped_sample = self.pending_sample
self.pending_sample = None
self.state = 'idle'
self.get_logger().info(
f'Skipped pending run by input "{reason}": '
f'direction={skipped_sample["direction"]:+d}, '
f'signed_target={skipped_sample["signed_target_angle_deg"]:.2f} deg, '
f'odom={skipped_sample["odom_angle_deg"]:.2f} deg, '
f'corrected={skipped_sample["corrected_angle_deg"]:.2f} deg, '
f'used_correction={skipped_sample["used_correction"]:.6f}. '
'This run will not be used in the final scale summary.'
)
def _record_pending_sample(self, ground_error_deg):
with self.samples_lock:
if self.pending_sample is None:
self.get_logger().warn(
'No pending successful run. Set start_test:=true first, wait for the robot to stop, '
'then enter the measured deg error.'
)
return
actual_angle_deg = self.pending_sample['target_angle_deg'] + ground_error_deg
if actual_angle_deg <= 0.0:
self.get_logger().error(
f'Invalid measured result: target + error = {actual_angle_deg:.2f} deg. '
'Re-enter the deg error for this pending run.'
)
return
sample = dict(self.pending_sample)
sample['ground_error_deg'] = ground_error_deg
sample['actual_angle_deg'] = actual_angle_deg
sample['scale'] = math.radians(actual_angle_deg) / math.radians(sample['odom_angle_deg'])
self.samples.append(sample)
sample_index = len(self.samples)
direction_index = sum(
1 for recorded_sample in self.samples
if recorded_sample['direction'] == sample['direction']
)
self.pending_sample = None
self.state = 'idle'
self.get_logger().info(
f'Recorded sample #{sample_index} overall, direction {sample["direction"]:+d} #{direction_index}: '
f'actual={actual_angle_deg:.2f} deg, '
f'ground_error={ground_error_deg:+.2f} deg, odom={sample["odom_angle_deg"]:.2f} deg, '
f'scale={sample["scale"]:.6f}. Set start_test:=true for the next run, or enter 0 to finish.'
)
def _print_summary(self):
with self.samples_lock:
samples = list(self.samples)
if not samples:
self.get_logger().warn('No successful calibration samples have been recorded yet.')
return
self.get_logger().info('========== YAW ODOM SCALE SUMMARY ==========')
for index, sample in enumerate(samples, start=1):
self.get_logger().info(
f'#{index:02d} direction={sample["direction"]:+d}, '
f'signed_target={sample["signed_target_angle_deg"]:.2f} deg, '
f'target={sample["target_angle_deg"]:.2f} deg, '
f'actual={sample["actual_angle_deg"]:.2f} deg, '
f'ground_error={sample["ground_error_deg"]:+.2f} deg, '
f'odom={sample["odom_angle_deg"]:.2f} deg, '
f'corrected={sample["corrected_angle_deg"]:.2f} deg, '
f'used_correction={sample["used_correction"]:.6f}, '
f'scale={sample["scale"]:.6f}'
)
self._print_scale_stats('all', samples)
for direction in (1, -1):
direction_samples = [sample for sample in samples if sample['direction'] == direction]
if direction_samples:
self._print_scale_stats(f'direction={direction:+d}', direction_samples)
self.get_logger().info('Restart this node to clear cached samples.')
def _print_scale_stats(self, label, samples):
scales = [sample['scale'] for sample in samples]
mean_scale = statistics.fmean(scales)
std_scale = statistics.pstdev(scales) if len(scales) > 1 else 0.0
self.get_logger().info(
f'{label}: samples={len(scales)}, recommended_odometry.scale_theta={mean_scale:.6f}, '
f'std={std_scale:.6f}, min={min(scales):.6f}, max={max(scales):.6f}'
)
def _publish_stop(self):
try:
self.cmd_vel_pub.publish(Twist())
except Exception:
pass
def _stop_robot(self):
for _ in range(STOP_REPEAT_COUNT):
self._publish_stop()
def _stop_robot_with_ros_cli(self):
topic = shlex.quote(self.cmd_vel_topic)
zero_twist = (
'"{linear: {x: 0.0, y: 0.0, z: 0.0}, '
'angular: {x: 0.0, y: 0.0, z: 0.0}}"'
)
os.system(
f'timeout 2s ros2 topic pub --once {topic} '
f'geometry_msgs/msg/Twist {zero_twist} >/dev/null 2>&1'
)
def _reset_start_test(self):
self.set_parameters([
Parameter('start_test', Parameter.Type.BOOL, False),
])
@staticmethod
def _yaw_from_quaternion(x, y, z, w):
siny_cosp = 2.0 * (w * z + x * y)
cosy_cosp = 1.0 - 2.0 * (y * y + z * z)
return math.atan2(siny_cosp, cosy_cosp)
def main(args=None):
rclpy.init(args=args)
node = OdomYawCalib()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node._stop_robot()
node._stop_robot_with_ros_cli()
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_calibration</name>
<version>0.0.0</version>
<description>AGV Pro calibration tools for odom, IMU, and TF health check</description>
<maintainer email="elephant@todo.todo">elephant</maintainer>
<license>TODO: License declaration</license>
<depend>rclpy</depend>
<depend>geometry_msgs</depend>
<depend>nav_msgs</depend>
<depend>sensor_msgs</depend>
<depend>tf2_ros</depend>
<depend>std_msgs</depend>
<depend>action_msgs</depend>
<depend>nav2_msgs</depend>
<depend>rcl_interfaces</depend>
<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>
<test_depend>ament_pep257</test_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
+4
View File
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/agv_pro_calibration
[install]
install_scripts=$base/lib/agv_pro_calibration
+29
View File
@@ -0,0 +1,29 @@
from setuptools import find_packages, setup
package_name = 'agv_pro_calibration'
setup(
name=package_name,
version='0.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='elephant',
maintainer_email='elephant@todo.todo',
description='AGV Pro calibration tools for odom, IMU, and TF health check',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'odom_linear_calib = agv_pro_calibration.odom_linear_calib:main',
'odom_yaw_calib = agv_pro_calibration.odom_yaw_calib:main',
'final_pose_refiner = agv_pro_calibration.final_pose_refiner:main',
'navigate_to_pose_refiner_proxy = agv_pro_calibration.navigate_to_pose_refiner_proxy:main',
],
},
)
@@ -0,0 +1,25 @@
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_copyright.main import main
import pytest
# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
+25
View File
@@ -0,0 +1,25 @@
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
+23
View File
@@ -0,0 +1,23 @@
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'
+1 -1
View File
@@ -2,7 +2,7 @@
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_description</name>
<version>1.0.1</version>
<version>1.0.8</version>
<description>
<p>URDF Description package for AGV pro</p>
</description>
+37
View File
@@ -0,0 +1,37 @@
cmake_minimum_required(VERSION 3.8)
project(agv_pro_msgs)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
find_package(std_msgs REQUIRED)
find_package(rosidl_default_generators REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
"msg/AGVProStatus.msg"
"srv/SetDigitalOutput.srv"
"srv/GetDigitalInput.srv"
"srv/SetLedColor.srv"
"srv/SetLedMode.srv"
DEPENDENCIES std_msgs
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
ament_package()
+6
View File
@@ -0,0 +1,6 @@
std_msgs/Header header
uint8 motor_status
uint8 motor_error
float64 battery_voltage
uint8 enable_status
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_msgs</name>
<version>1.0.8</version>
<description>TODO: Package description</description>
<maintainer email="weijun.xie@elephantrobotics.com">lanni</maintainer>
<license>TODO: License declaration</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>std_msgs</depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
import rclpy
import time
from rclpy.node import Node
from agv_pro_msgs.srv import (
SetDigitalOutput,
GetDigitalInput,
SetLedColor,
SetLedMode
)
class AGVIOClient(Node):
def __init__(self):
super().__init__('agv_io_client')
# Create service client
self.cli_set_io = self.create_client(SetDigitalOutput, 'set_digital_output')
self.cli_get_io = self.create_client(GetDigitalInput, 'get_digital_input')
self.cli_led_output = self.create_client(SetLedColor, 'set_led_color')
self.cli_led_mode = self.create_client(SetLedMode, 'set_led_mode')
# Wait until all services are available
self._wait_for_services()
def _wait_for_services(self):
"""Wait for all services to become available."""
clients = [
self.cli_set_io,
self.cli_get_io,
self.cli_led_output,
self.cli_led_mode
]
for cli in clients:
while not cli.wait_for_service(timeout_sec=1.0):
pass
def _call_service(self, client, request):
future = client.call_async(request)
rclpy.spin_until_future_complete(self, future, timeout_sec=5.0)
if future.result() is not None:
return future.result()
else:
self.get_logger().error(f'Service call failed: {future.exception()}')
return None
# ------------------------------
# Set digital output
# ------------------------------
def set_digital_output(self, pin: int, state: int) -> bool:
"""Set digital output pin state."""
req = SetDigitalOutput.Request()
req.pin = pin
req.state = state
res = self._call_service(self.cli_set_io, req)
return res.success if res else False
# ------------------------------
# Get digital input
# ------------------------------
def get_digital_input(self, pin: int):
"""Read digital input pin state."""
req = GetDigitalInput.Request()
req.pin = pin
res = self._call_service(self.cli_get_io, req)
return res.state if (res and res.success) else None
# ------------------------------
# Set LED color
# ------------------------------
def set_led_color(self,
position: int,
brightness: int,
r: int,
g: int,
b: int) -> bool:
"""Set LED RGB color and brightness."""
req = SetLedColor.Request()
req.position = position
req.brightness = brightness
req.r = r
req.g = g
req.b = b
res = self._call_service(self.cli_led_output, req)
return res.success if res else False
# ------------------------------
# Set LED mode
# ------------------------------
def set_led_mode(self, mode: bool) -> bool:
"""Set LED mode (True/False)."""
req = SetLedMode.Request()
req.mode = mode
res = self._call_service(self.cli_led_mode, req)
return res.success if res else False
def main(args=None):
rclpy.init(args=args)
client = AGVIOClient()
################
# Example usage:
################
# client.set_digital_output(pin=1, state=1)
# client.get_digital_input(pin=2)
# client.set_led_mode(True)
# for i in range(10):
# client.set_led_color(0, 100, 255, 255, 0)
# client.set_led_color(1, 100, 255, 255, 0)
# time.sleep(0.5)
# client.set_led_color(0, 0, 0, 0, 0)
# client.set_led_color(1, 0, 0, 0, 0)
# time.sleep(0.5)
# client.set_led_color(0, 100, 255, 255, 0)
# client.set_led_color(1, 100, 255, 255, 0)
# client.set_led_mode(True)
client.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
+5
View File
@@ -0,0 +1,5 @@
int32 pin
---
bool success
int32 state
string message
+5
View File
@@ -0,0 +1,5 @@
int32 pin
int32 state
---
bool success
string message
+8
View File
@@ -0,0 +1,8 @@
int32 position
int32 brightness
int32 r
int32 g
int32 b
---
bool success
string message
+4
View File
@@ -0,0 +1,4 @@
bool mode
---
bool success
string message
@@ -3,36 +3,28 @@ import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from launch.actions import DeclareLaunchArgument,IncludeLaunchDescription
from launch.actions import DeclareLaunchArgument, GroupAction, IncludeLaunchDescription
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node, SetRemap
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
use_rviz = LaunchConfiguration('use_rviz', default='true')
map_dir = LaunchConfiguration(
'map',
default=os.path.join(
get_package_share_directory('agv_pro_navigation2'),
'map',
'map.yaml'))
default=os.path.join(get_package_share_directory('agv_pro_navigation2'), 'map', 'map.yaml'))
param_file_name = 'agvpro.yaml'
param_dir = LaunchConfiguration(
'params_file',
default=os.path.join(
get_package_share_directory('agv_pro_navigation2'),
'param',
param_file_name))
default=os.path.join(get_package_share_directory('agv_pro_navigation2'), 'param', param_file_name))
nav2_launch_file_dir = os.path.join(get_package_share_directory('nav2_bringup'), 'launch')
rviz_config_dir = os.path.join(
get_package_share_directory('agv_pro_navigation2'),
'rviz',
'agvpro_navigation2.rviz')
rviz_config_dir = os.path.join(get_package_share_directory('agv_pro_navigation2'), 'rviz', 'agvpro_navigation2.rviz')
return LaunchDescription([
DeclareLaunchArgument(
@@ -45,12 +37,41 @@ def generate_launch_description():
default_value=param_dir,
description='Full path to param file to load'),
IncludeLaunchDescription(
PythonLaunchDescriptionSource([nav2_launch_file_dir, '/bringup_launch.py']),
launch_arguments={
'map': map_dir,
'params_file': param_dir}.items(),
),
GroupAction(actions=[SetRemap(
src='/goal_pose',
dst='/goal_pose_nav2',
)] + [
SetRemap(
src=f'/{action}/_action/{suffix}',
dst=f'/{action}_nav2/_action/{suffix}')
for action in ('navigate_to_pose', 'navigate_through_poses')
for suffix in ('send_goal', 'get_result', 'cancel_goal', 'feedback', 'status')
] + [
IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_launch_file_dir, '/bringup_launch.py']),
launch_arguments={
'map': map_dir,
'params_file': param_dir,
}.items()),
], scoped=True),
Node(
package='agv_pro_calibration',
executable='navigate_to_pose_refiner_proxy',
name='navigate_to_pose_refiner_proxy',
output='screen',
parameters=[{'use_sim_time': use_sim_time}]),
Node(
package='agv_pro_calibration',
executable='final_pose_refiner',
name='final_pose_refiner',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'final_pose_refiner_auto_start_on_nav_success': False,
}]),
Node(
package='rviz2',
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,7 +1,7 @@
image: map.pgm
mode: trinary
resolution: 0.05
origin: [-10, -24.4, 0]
origin: [-22.8, -10, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
image: map1.pgm
mode: trinary
resolution: 0.05
origin: [-10, -10, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
image: map.pgm
mode: trinary
resolution: 0.05
origin: [-21.2, -22.8, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25
+1 -1
View File
@@ -2,7 +2,7 @@
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>agv_pro_navigation2</name>
<version>1.0.1</version>
<version>1.0.8</version>
<description>ROS2 launch scripts for navigation2</description>
<maintainer email="weijun.xie@elephantrobotics.com">lanni</maintainer>
<license>BSD-3-Clause license</license>
+72 -31
View File
@@ -14,10 +14,13 @@ amcl:
global_frame_id: "map"
lambda_short: 0.1
laser_likelihood_max_dist: 2.0
laser_max_range: 100.0
laser_min_range: -1.0
# 激光匹配最大有效距离 / Maximum valid laser matching range, 限制远距离无效数据对粒子权重的影响 / limits the effect of invalid distant data on particle weights, 初始值 / Initial value: 100.0 m
laser_max_range: 10.0
# 激光匹配最小有效距离 / Minimum valid laser matching range, 过滤雷达近距离盲区数据 / filters data in the lidar near-field blind zone, 初始值 / Initial value: -1.0
laser_min_range: 0.2
laser_model_type: "likelihood_field"
max_beams: 60
# 每次定位更新采样的激光束数量 / Number of laser beams sampled per localization update, 增加定位匹配所使用的观测信息 / increases observation information used for localization matching, 初始值 / Initial value: 60
max_beams: 90
max_particles: 2000
min_particles: 500
odom_frame_id: "odom"
@@ -25,14 +28,19 @@ amcl:
pf_z: 0.99
recovery_alpha_fast: 0.0
recovery_alpha_slow: 0.0
resample_interval: 2
robot_model_type: "nav2_amcl::OmniMotionModel"
# 粒子滤波重采样间隔 / Particle filter resampling interval, 控制定位重采样与收敛更新频率 / controls localization resampling and convergence update frequency, 初始值 / Initial value: 2
resample_interval: 1
# 里程计运动模型类型 / Odometry motion model type, 定义机器人运动噪声与粒子位姿预测模型 / defines robot motion noise and particle pose prediction model, 初始值 / Initial value: nav2_amcl::OmniMotionModel
robot_model_type: "nav2_amcl::DifferentialMotionModel"
save_pose_rate: 0.5
sigma_hit: 0.02
# 激光命中模型标准差 / Laser hit model standard deviation, 调节激光观测偏差对粒子权重的敏感程度 / adjusts particle-weight sensitivity to laser observation error, 初始值 / Initial value: 0.02
sigma_hit: 0.04
tf_broadcast: true
transform_tolerance: 0.3
update_min_a: 0.06
update_min_d: 0.025
# 触发定位更新的最小旋转角度 / Minimum rotation angle triggering a localization update, 控制小角度运动时激光定位更新频率 / controls laser localization update frequency during small-angle motion, 初始值 / Initial value: 0.06 rad
update_min_a: 0.04
# 触发定位更新的最小平移距离 / Minimum translation distance triggering a localization update, 控制低速平移时激光定位更新频率 / controls laser localization update frequency during low-speed translation, 初始值 / Initial value: 0.025 m
update_min_d: 0.015
z_hit: 0.7
z_max: 0.001
z_rand: 0.059
@@ -109,11 +117,11 @@ bt_navigator_rclcpp_node:
controller_server:
ros__parameters:
use_sim_time: False
controller_frequency: 5.0
controller_frequency: 20.0
min_x_velocity_threshold: 0.001
min_y_velocity_threshold: 0.5
min_theta_velocity_threshold: 0.001
failure_tolerance: 3.0
failure_tolerance: 0.3
progress_checker_plugin: "progress_checker"
goal_checker_plugins: ["general_goal_checker"] # "precise_goal_checker"
controller_plugins: ["FollowPath"]
@@ -121,8 +129,8 @@ controller_server:
# Progress checker parameters
progress_checker:
plugin: "nav2_controller::SimpleProgressChecker"
required_movement_radius: 0.5
movement_time_allowance: 10.0
required_movement_radius: 0.15
movement_time_allowance: 8.0
# Goal checker parameters
#precise_goal_checker:
# plugin: "nav2_controller::SimpleGoalChecker"
@@ -132,13 +140,15 @@ controller_server:
general_goal_checker:
stateful: True
plugin: "nav2_controller::SimpleGoalChecker"
xy_goal_tolerance: 0.25
yaw_goal_tolerance: 0.25
# 到达目标的位置容差 / Goal position tolerance, 判定机器人位置是否满足导航完成条件 / determines whether robot position satisfies navigation completion, 初始值 / Initial value: 0.25 m
xy_goal_tolerance: 0.05
# 到达目标的航向角容差 / Goal heading tolerance, 判定机器人姿态是否满足导航完成条件 / determines whether robot orientation satisfies navigation completion, 初始值 / Initial value: 0.25 rad
yaw_goal_tolerance: 0.8
# DWB parameters
FollowPath:
plugin: "dwb_core::DWBLocalPlanner"
debug_trajectory_details: True
min_vel_x: 0.0
min_vel_x: -0.03
min_vel_y: 0.0
max_vel_x: 0.26
max_vel_y: 0.0
@@ -150,26 +160,28 @@ controller_server:
# https://github.com/ROBOTIS-GIT/turtlebot3_simulations/issues/75
acc_lim_x: 2.5
acc_lim_y: 0.0
acc_lim_theta: 0.25
acc_lim_theta: 2.5
decel_lim_x: -2.5
decel_lim_y: 0.0
decel_lim_theta: -0.25
decel_lim_theta: -2.5
vx_samples: 20
vy_samples: 5
vtheta_samples: 20
vtheta_samples: 40
sim_time: 1.7
linear_granularity: 0.05
angular_granularity: 0.025
transform_tolerance: 0.1
xy_goal_tolerance: 0.25
trans_stopped_velocity: 0.1
# DWB 进入目标姿态调整模式的位置容差 / Position tolerance for DWB goal-orientation adjustment mode, 控制路径跟踪切换到末端旋转控制的距离窗口 / controls the distance window for switching from path tracking to final rotation control, 初始值 / Initial value: 0.25 m
xy_goal_tolerance: 0.03
# 判定平移停止的速度阈值 / Velocity threshold for considering translation stopped, 控制进入仅旋转控制前的平移停止条件 / controls the translation-stop condition before rotate-only control, 初始值 / Initial value: 0.1 m/s
trans_stopped_velocity: 0.01
short_circuit_trajectory_evaluation: True
stateful: True
critics: ["RotateToGoal", "Oscillation", "BaseObstacle", "GoalAlign", "PathAlign", "PathDist", "GoalDist"]
BaseObstacle.scale: 0.02
PathAlign.scale: 32.0
PathAlign.scale: 23.0
PathAlign.forward_point_distance: 0.1
GoalAlign.scale: 24.0
GoalAlign.scale: 18.0
GoalAlign.forward_point_distance: 0.1
PathDist.scale: 32.0
GoalDist.scale: 24.0
@@ -197,8 +209,8 @@ local_costmap:
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 5.0
inflation_radius: 0.25
cost_scaling_factor: 4.0
inflation_radius: 0.30
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
@@ -232,12 +244,12 @@ local_costmap:
global_costmap:
global_costmap:
ros__parameters:
update_frequency: 0.3
publish_frequency: 0.3
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_footprint
use_sim_time: False
robot_radius: 0.22
footprint: "[[0.26, 0.18], [0.26, -0.18], [-0.26, -0.18], [-0.26, 0.18]]"
resolution: 0.05
track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
@@ -260,8 +272,8 @@ global_costmap:
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 5.0
inflation_radius: 0.25
cost_scaling_factor: 4.0
inflation_radius: 0.30
always_send_full_costmap: True
global_costmap_client:
ros__parameters:
@@ -273,7 +285,9 @@ global_costmap:
map_server:
ros__parameters:
use_sim_time: False
yaml_filename: "turtlebot3_world.yaml"
# Overridden in launch by the "map" launch configuration or provided default value.
# To use in yaml, remove the default "map" value in the navigation2_active.launch.py file & provide full path to map below.
yaml_filename: ""
map_saver:
ros__parameters:
@@ -290,14 +304,26 @@ planner_server:
planner_plugins: ["GridBased"]
GridBased:
plugin: "nav2_navfn_planner/NavfnPlanner"
tolerance: 2.0
# 全局规划终点替代容差 / Global planner substitute-goal tolerance, 目标点不可达时限定可接受替代终点的距离范围 / limits the acceptable substitute-goal distance when the goal is unreachable, 初始值 / Initial value: 2.0 m
tolerance: 0.05
use_astar: false
# 是否允许路径经过未知区域 / Whether paths may traverse unknown space, 控制全局规划器能否使用未观测栅格 / controls whether the global planner may use unobserved cells, 初始值 / Initial value: true
allow_unknown: true
planner_server_rclcpp_node:
ros__parameters:
use_sim_time: False
smoother_server:
ros__parameters:
use_sim_time: True
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: True
recoveries_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
@@ -332,3 +358,18 @@ waypoint_follower:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: True
waypoint_pause_duration: 200
velocity_smoother:
ros__parameters:
use_sim_time: True
smoothing_frequency: 20.0
scale_velocities: False
feedback: "OPEN_LOOP"
max_velocity: [0.26, 0.0, 0.5]
min_velocity: [-0.26, 0.0, -0.5]
max_accel: [2.5, 0.0, 3.2]
max_decel: [-2.5, 0.0, -3.2]
odom_topic: "odom"
odom_duration: 0.1
deadband_velocity: [0.0, 0.0, 0.0]
velocity_timeout: 1.0
@@ -1,17 +1,31 @@
#! /usr/bin/env python3
import argparse
import sys
import yaml
import rclpy
from geometry_msgs.msg import PoseStamped
from nav2_simple_commander.robot_navigator import BasicNavigator, TaskResult
import rclpy
from rclpy.duration import Duration
"""
Basic navigation demo to go to pose.
"""
def parse_arguments():
parser = argparse.ArgumentParser(description='Send navigation test goals.')
parser.add_argument(
'targets',
nargs='*',
help='Waypoint letters to execute once, for example AB. Omit to loop ABCDE.')
return parser.parse_args()
def set_initial_pose(navigator: BasicNavigator, x: float, y: float, oz: float, ow: float):
"""
Set the initial pose of the robot for AMCL localization.
Set the initial pose of the robot for the active localization backend.
Args:
navigator (BasicNavigator): The navigator instance controlling the robot.
@@ -30,21 +44,7 @@ def set_initial_pose(navigator: BasicNavigator, x: float, y: float, oz: float, o
navigator.setInitialPose(initial_pose)
def navigate_to_goal(navigator: BasicNavigator, x: float, y: float, oz: float, ow: float, verbose: bool = False) -> bool:
"""
Navigate the robot to a target goal pose.
Args:
navigator (BasicNavigator): The navigator instance controlling the robot.
x (float): Goal X position in the map frame.
y (float): Goal Y position in the map frame.
oz (float): Orientation Z component (quaternion).
ow (float): Orientation W component (quaternion).
verbose (bool, optional): If True, prints navigation feedback such as estimated arrival time. Default is False.
Returns:
bool: True if navigation succeeded, False otherwise.
"""
def make_goal_pose(navigator: BasicNavigator, x: float, y: float, oz: float, ow: float) -> PoseStamped:
goal_pose = PoseStamped()
goal_pose.header.frame_id = 'map'
goal_pose.header.stamp = navigator.get_clock().now().to_msg()
@@ -52,6 +52,22 @@ def navigate_to_goal(navigator: BasicNavigator, x: float, y: float, oz: float, o
goal_pose.pose.position.y = y
goal_pose.pose.orientation.z = oz
goal_pose.pose.orientation.w = ow
return goal_pose
def navigate_to_goal(navigator: BasicNavigator, goal_pose: PoseStamped, verbose: bool = False) -> bool:
"""
Navigate the robot to a target goal pose.
Args:
navigator (BasicNavigator): The navigator instance controlling the robot.
goal_pose (PoseStamped): Goal pose in the map frame.
verbose (bool, optional): If True, prints navigation feedback such as estimated arrival time. Default is False.
Returns:
bool: True if navigation succeeded, False otherwise.
"""
goal_pose.header.stamp = navigator.get_clock().now().to_msg()
navigator.goToPose(goal_pose)
@@ -74,24 +90,71 @@ def navigate_to_goal(navigator: BasicNavigator, x: float, y: float, oz: float, o
return False
if __name__ == '__main__':
cli_args = parse_arguments()
rclpy.init()
navigator = BasicNavigator()
# Set robot initial pose
# set_initial_pose(navigator, x=-1.9248794317245483, y=-0.5366987586021423, oz=-1.8463129131030735e-06, ow=0.9999999999982956)
# AMCL obtains its initial origin pose from agvpro.yaml.
navigator.initial_pose_received = True
navigator.waitUntilNav2Active()
# Wait for navigation to fully activate, since autostarting nav2
# navigator.waitUntilNav2Active()
# Try to load waypoints from YAML, fallback to hardcoded defaults
waypoints = {}
try:
with open('waypoints.yaml', 'r') as f:
waypoints = (yaml.safe_load(f) or {}).get('waypoints', {})
except FileNotFoundError:
with open('waypoints.yaml', 'w') as f:
yaml.dump({'waypoints': {}}, f, default_flow_style=False)
goal_A = [1.6766083240509033,0.37930558800697327,-0.03491306994337919, 0.9993903529387947]
goal_B = [-0.5062443017959595,1.559376835823059,0.6869307039904945,0.7267229237578264]
goals = {
'A': waypoints.get('A', [4.89649,-0.617371,0.706899,0.707315]),
'B': waypoints.get('B', [0.90387,-0.446105,0.273676,0.961822]),
'C': waypoints.get('C', [4.46734,-0.532388,0.969886,-0.243558]),
'D': waypoints.get('D', [-0.0233348,0.00798563,0.999322,0.0368173]),
'E': waypoints.get('E', [2.33651,-0.440663,0.937234,-0.3487]),
}
x_goal, y_goal, orientation_z, orientation_w = goal_A
success = navigate_to_goal(navigator, x_goal, y_goal, orientation_z, orientation_w)
print("Navigation result:", success)
args = cli_args.targets
loop_targets = False
if args:
targets = []
for arg in args:
for c in arg.upper():
if c in goals:
targets.append(c)
else:
targets = ['A', 'B', 'C', 'D', 'E']
loop_targets = True
print('No target arguments provided; running A-B-C-D-E repeatedly. Press Ctrl+C to stop.')
x_goal, y_goal, orientation_z, orientation_w = goal_B
success = navigate_to_goal(navigator, x_goal, y_goal, orientation_z, orientation_w)
print("Navigation result:", success)
if not targets:
print('No valid target names provided. Use names such as A, B, C, D, E or AB.')
rclpy.shutdown()
sys.exit(1)
rclpy.shutdown()
try:
cycle_index = 1
while rclpy.ok():
if loop_targets:
print(f'============= cycle {cycle_index}: ABCDE =============')
for name in targets:
if not rclpy.ok():
break
x_goal, y_goal, orientation_z, orientation_w = goals[name]
input(f'============={name}==================\n')
goal_pose = make_goal_pose(navigator, x_goal, y_goal, orientation_z, orientation_w)
success = navigate_to_goal(navigator, goal_pose)
print("Navigation result:", goals[name], success)
if not loop_targets:
break
cycle_index += 1
except KeyboardInterrupt:
print('Navigation loop interrupted by user.')
navigator.cancelTask()
finally:
if rclpy.ok():
rclpy.shutdown()
+3
View File
@@ -0,0 +1,3 @@
from pymycobot import MyAGVPro
m = MyAGVPro('/dev/agvpro_controller')
m.power_on()
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Record waypoints by sampling stable map->base_footprint pose."""
import sys
import threading
import time
import rclpy
from rclpy.node import Node
from tf2_ros import Buffer, TransformListener
import yaml
class WaypointRecorder(Node):
def __init__(self):
super().__init__('waypoint_recorder')
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.yaml_path = 'waypoints.yaml'
self.waypoints = {}
self._load_existing()
def _load_existing(self):
try:
with open(self.yaml_path, 'r') as f:
data = yaml.safe_load(f) or {}
self.waypoints = data.get('waypoints', {})
n = len(self.waypoints)
if n > 0:
self.get_logger().info(f'Loaded {n} existing waypoints from {self.yaml_path}')
except FileNotFoundError:
self.waypoints = {}
def _save(self):
data = {'waypoints': self.waypoints}
with open(self.yaml_path, 'w') as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
self.get_logger().info(f'Saved waypoints to {self.yaml_path}')
def _sample_pose(self, duration_sec=3.0, rate_hz=20):
xs, ys, zs, ws = [], [], [], []
dt = 1.0 / rate_hz
start = time.time()
while time.time() - start < duration_sec:
try:
trans = self.tf_buffer.lookup_transform(
'map', 'base_footprint', rclpy.time.Time()
)
t = trans.transform.translation
r = trans.transform.rotation
xs.append(t.x)
ys.append(t.y)
zs.append(r.z)
ws.append(r.w)
except Exception:
pass
time.sleep(dt)
if not xs:
return None
xs.sort()
ys.sort()
zs.sort()
ws.sort()
n = len(xs)
mid = n // 2
if n % 2 == 1:
return [xs[mid], ys[mid], zs[mid], ws[mid]]
return [
(xs[mid - 1] + xs[mid]) / 2,
(ys[mid - 1] + ys[mid]) / 2,
(zs[mid - 1] + zs[mid]) / 2,
(ws[mid - 1] + ws[mid]) / 2,
]
def run(self):
self.get_logger().info('Waypoint recorder ready.')
self.get_logger().info('Enter A/B/C/D/E to record, q to quit.')
while rclpy.ok():
try:
cmd = input('> ').strip().upper()
except EOFError:
break
if cmd == 'Q':
break
if cmd in 'ABCDE':
self.get_logger().info(
f'Sampling pose for {cmd} ({3}s, keep still)...'
)
pose = self._sample_pose()
if pose is None:
self.get_logger().error(
'Failed to sample pose. Is AMCL running?'
)
continue
self.waypoints[cmd] = [float(f'{v:.6f}') for v in pose]
self.get_logger().info(f'{cmd}: {self.waypoints[cmd]}')
self._save()
else:
self.get_logger().warn('Use A/B/C/D/E or q.')
def main(args=None):
rclpy.init(args=args)
node = WaypointRecorder()
spin_thread = threading.Thread(target=rclpy.spin, args=(node,), daemon=True)
spin_thread.start()
try:
node.run()
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,26 @@
waypoints:
A:
- 4.24531
- 1.866955
- 0.584964
- 0.811059
B:
- 3.624886
- -2.221018
- -0.569358
- 0.82209
C:
- 1.900274
- 1.940145
- -0.737521
- 0.675324
D:
- 0.882323
- -0.456797
- 0.745742
- 0.666235
E:
- -1.63798
- -0.847909
- 0.978385
- 0.206792
+3
View File
@@ -0,0 +1,3 @@
.vscode
build
__pycache__
+308
View File
@@ -0,0 +1,308 @@
// Tencent is pleased to support the open source community by making RapidJSON
// available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
// rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License
// at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef RAPIDJSON_ALLOCATORS_H_
#define RAPIDJSON_ALLOCATORS_H_
#include "rapidjson.h"
RAPIDJSON_NAMESPACE_BEGIN
///////////////////////////////////////////////////////////////////////////////
// Allocator
/*! \class rapidjson::Allocator
\brief Concept for allocating, resizing and freeing memory block.
Note that Malloc() and Realloc() are non-static but Free() is static.
So if an allocator need to support Free(), it needs to put its pointer in
the header of memory block.
\code
concept Allocator {
static const bool kNeedFree; //!< Whether this allocator needs to call
Free().
// Allocate a memory block.
// \param size of the memory block in bytes.
// \returns pointer to the memory block.
void* Malloc(size_t size);
// Resize a memory block.
// \param originalPtr The pointer to current memory block. Null pointer is
permitted.
// \param originalSize The current size in bytes. (Design issue: since some
allocator may not book-keep this, explicitly pass to it can save memory.)
// \param newSize the new size in bytes.
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
// Free a memory block.
// \param pointer to the memory block. Null pointer is permitted.
static void Free(void *ptr);
};
\endcode
*/
/*! \def RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY
\ingroup RAPIDJSON_CONFIG
\brief User-defined kDefaultChunkCapacity definition.
User can define this as any \c size that is a power of 2.
*/
#ifndef RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY
#define RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY (64 * 1024)
#endif
///////////////////////////////////////////////////////////////////////////////
// CrtAllocator
//! C-runtime library allocator.
/*! This class is just wrapper for standard C library memory routines.
\note implements Allocator concept
*/
class CrtAllocator {
public:
static const bool kNeedFree = true;
void *Malloc(size_t size) {
if (size) // behavior of malloc(0) is implementation defined.
return std::malloc(size);
else
return NULL; // standardize to returning NULL.
}
void *Realloc(void *originalPtr, size_t originalSize, size_t newSize) {
(void)originalSize;
if (newSize == 0) {
std::free(originalPtr);
return NULL;
}
return std::realloc(originalPtr, newSize);
}
static void Free(void *ptr) { std::free(ptr); }
};
///////////////////////////////////////////////////////////////////////////////
// MemoryPoolAllocator
//! Default memory allocator used by the parser and DOM.
/*! This allocator allocate memory blocks from pre-allocated memory chunks.
It does not free memory blocks. And Realloc() only allocate new memory.
The memory chunks are allocated by BaseAllocator, which is CrtAllocator by
default.
User may also supply a buffer as the first chunk.
If the user-buffer is full then additional chunks are allocated by
BaseAllocator.
The user-buffer is not deallocated by this allocator.
\tparam BaseAllocator the allocator type for allocating memory chunks.
Default is CrtAllocator. \note implements Allocator concept
*/
template <typename BaseAllocator = CrtAllocator>
class MemoryPoolAllocator {
public:
static const bool kNeedFree =
false; //!< Tell users that no need to call Free() with this allocator.
//!< (concept Allocator)
//! Constructor with chunkSize.
/*! \param chunkSize The size of memory chunk. The default is
kDefaultChunkSize. \param baseAllocator The allocator for allocating memory
chunks.
*/
MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity,
BaseAllocator *baseAllocator = 0)
: chunkHead_(0),
chunk_capacity_(chunkSize),
userBuffer_(0),
baseAllocator_(baseAllocator),
ownBaseAllocator_(0) {}
//! Constructor with user-supplied buffer.
/*! The user buffer will be used firstly. When it is full, memory pool
allocates new chunk with chunk size.
The user buffer will not be deallocated when this allocator is destructed.
\param buffer User supplied buffer.
\param size Size of the buffer in bytes. It must at least larger than
sizeof(ChunkHeader). \param chunkSize The size of memory chunk. The default
is kDefaultChunkSize. \param baseAllocator The allocator for allocating
memory chunks.
*/
MemoryPoolAllocator(void *buffer, size_t size,
size_t chunkSize = kDefaultChunkCapacity,
BaseAllocator *baseAllocator = 0)
: chunkHead_(0),
chunk_capacity_(chunkSize),
userBuffer_(buffer),
baseAllocator_(baseAllocator),
ownBaseAllocator_(0) {
RAPIDJSON_ASSERT(buffer != 0);
RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
chunkHead_ = reinterpret_cast<ChunkHeader *>(buffer);
chunkHead_->capacity = size - sizeof(ChunkHeader);
chunkHead_->size = 0;
chunkHead_->next = 0;
}
//! Destructor.
/*! This deallocates all memory chunks, excluding the user-supplied buffer.
*/
~MemoryPoolAllocator() {
Clear();
RAPIDJSON_DELETE(ownBaseAllocator_);
}
//! Deallocates all memory chunks, excluding the user-supplied buffer.
void Clear() {
while (chunkHead_ && chunkHead_ != userBuffer_) {
ChunkHeader *next = chunkHead_->next;
baseAllocator_->Free(chunkHead_);
chunkHead_ = next;
}
if (chunkHead_ && chunkHead_ == userBuffer_)
chunkHead_->size = 0; // Clear user buffer
}
//! Computes the total capacity of allocated memory chunks.
/*! \return total capacity in bytes.
*/
size_t Capacity() const {
size_t capacity = 0;
for (ChunkHeader *c = chunkHead_; c != 0; c = c->next)
capacity += c->capacity;
return capacity;
}
//! Computes the memory blocks allocated.
/*! \return total used bytes.
*/
size_t Size() const {
size_t size = 0;
for (ChunkHeader *c = chunkHead_; c != 0; c = c->next) size += c->size;
return size;
}
//! Allocates a memory block. (concept Allocator)
void *Malloc(size_t size) {
if (!size) return NULL;
size = RAPIDJSON_ALIGN(size);
if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
return NULL;
void *buffer = reinterpret_cast<char *>(chunkHead_) +
RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
chunkHead_->size += size;
return buffer;
}
//! Resizes a memory block (concept Allocator)
void *Realloc(void *originalPtr, size_t originalSize, size_t newSize) {
if (originalPtr == 0) return Malloc(newSize);
if (newSize == 0) return NULL;
originalSize = RAPIDJSON_ALIGN(originalSize);
newSize = RAPIDJSON_ALIGN(newSize);
// Do not shrink if new size is smaller than original
if (originalSize >= newSize) return originalPtr;
// Simply expand it if it is the last allocation and there is sufficient
// space
if (originalPtr ==
reinterpret_cast<char *>(chunkHead_) +
RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size -
originalSize) {
size_t increment = static_cast<size_t>(newSize - originalSize);
if (chunkHead_->size + increment <= chunkHead_->capacity) {
chunkHead_->size += increment;
return originalPtr;
}
}
// Realloc process: allocate and copy memory, do not free original buffer.
if (void *newBuffer = Malloc(newSize)) {
if (originalSize) std::memcpy(newBuffer, originalPtr, originalSize);
return newBuffer;
} else
return NULL;
}
//! Frees a memory block (concept Allocator)
static void Free(void *ptr) { (void)ptr; } // Do nothing
private:
//! Copy constructor is not permitted.
MemoryPoolAllocator(const MemoryPoolAllocator &rhs) /* = delete */;
//! Copy assignment operator is not permitted.
MemoryPoolAllocator &operator=(const MemoryPoolAllocator &rhs) /* = delete */;
//! Creates a new chunk.
/*! \param capacity Capacity of the chunk in bytes.
\return true if success.
*/
bool AddChunk(size_t capacity) {
if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator)();
if (ChunkHeader *chunk =
reinterpret_cast<ChunkHeader *>(baseAllocator_->Malloc(
RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
chunk->capacity = capacity;
chunk->size = 0;
chunk->next = chunkHead_;
chunkHead_ = chunk;
return true;
} else
return false;
}
static const int kDefaultChunkCapacity =
RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity.
//! Chunk header for perpending to each chunk.
/*! Chunks are stored as a singly linked list.
*/
struct ChunkHeader {
size_t capacity; //!< Capacity of the chunk in bytes (excluding the header
//!< itself).
size_t size; //!< Current size of allocated memory in bytes.
ChunkHeader *next; //!< Next chunk in the linked list.
};
ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head
//!< chunk serves allocation.
size_t chunk_capacity_; //!< The minimum capacity of chunk when they are
//!< allocated.
void *userBuffer_; //!< User supplied buffer.
BaseAllocator
*baseAllocator_; //!< base allocator for allocating memory chunks.
BaseAllocator *ownBaseAllocator_; //!< base allocator created by this object.
};
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_ENCODINGS_H_
@@ -0,0 +1,81 @@
// Tencent is pleased to support the open source community by making RapidJSON
// available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
// rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License
// at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef RAPIDJSON_CURSORSTREAMWRAPPER_H_
#define RAPIDJSON_CURSORSTREAMWRAPPER_H_
#include "stream.h"
#if defined(__GNUC__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#if defined(_MSC_VER) && _MSC_VER <= 1800
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(4702) // unreachable code
RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Cursor stream wrapper for counting line and column number if error exists.
/*!
\tparam InputStream Any stream that implements Stream Concept
*/
template <typename InputStream, typename Encoding = UTF8<>>
class CursorStreamWrapper : public GenericStreamWrapper<InputStream, Encoding> {
public:
typedef typename Encoding::Ch Ch;
CursorStreamWrapper(InputStream &is)
: GenericStreamWrapper<InputStream, Encoding>(is), line_(1), col_(0) {}
// counting line and column number
Ch Take() {
Ch ch = this->is_.Take();
if (ch == '\n') {
line_++;
col_ = 0;
} else {
col_++;
}
return ch;
}
//! Get the error line number, if error exists.
size_t GetLine() const { return line_; }
//! Get the error column number, if error exists.
size_t GetColumn() const { return col_; }
private:
size_t line_; //!< Current Line
size_t col_; //!< Current Column
};
#if defined(_MSC_VER) && _MSC_VER <= 1800
RAPIDJSON_DIAG_POP
#endif
#if defined(__GNUC__)
RAPIDJSON_DIAG_POP
#endif
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_

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