diff --git a/ros2_ws/src/cmd_vel_mux b/ros2_ws/src/cmd_vel_mux deleted file mode 160000 index bf9f4ce..0000000 --- a/ros2_ws/src/cmd_vel_mux +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bf9f4ce6ebfa04906d09d58b53af8302f68b9e2d diff --git a/ros2_ws/src/cmd_vel_mux/.cproject b/ros2_ws/src/cmd_vel_mux/.cproject new file mode 100644 index 0000000..ad7c0d2 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/.cproject @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/cmd_vel_mux/.gitignore b/ros2_ws/src/cmd_vel_mux/.gitignore new file mode 100644 index 0000000..4f8eb10 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/.gitignore @@ -0,0 +1,4 @@ +/bin +/build +/lib +**/__pycache__ diff --git a/ros2_ws/src/cmd_vel_mux/.project b/ros2_ws/src/cmd_vel_mux/.project new file mode 100644 index 0000000..7b3725c --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/.project @@ -0,0 +1,85 @@ + + + yocs_cmd_vel_mux + + + + + + org.python.pydev.PyDevBuilder + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + org.python.pydev.pythonNature + + diff --git a/ros2_ws/src/cmd_vel_mux/.pydevproject b/ros2_ws/src/cmd_vel_mux/.pydevproject new file mode 100644 index 0000000..a9cca03 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/.pydevproject @@ -0,0 +1,7 @@ + + + + +Default +python 2.7 + diff --git a/ros2_ws/src/cmd_vel_mux/.settings/language.settings.xml b/ros2_ws/src/cmd_vel_mux/.settings/language.settings.xml new file mode 100644 index 0000000..f227359 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/.settings/language.settings.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/ros2_ws/src/cmd_vel_mux/CHANGELOG.rst b/ros2_ws/src/cmd_vel_mux/CHANGELOG.rst new file mode 100644 index 0000000..609c818 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/CHANGELOG.rst @@ -0,0 +1,83 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package yocs_cmd_vel_mux +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.6.3 (2014-12-05) +------------------ + +0.6.2 (2014-11-30) +------------------ +* yocs_cmd_vel_mux: fixes node handle for output pub + to keep backwards compatibility +* adds a little launcher restructing for muxer and smoother +* Contributors: Marcus Liebhardt + +0.6.0 (2014-07-08) +------------------ +* updating package informations. remove email for authors. updating maintainer +* Contributors: Jihoon Lee + +0.5.3 (2014-03-24) +------------------ +* Added support for YAML-CPP 0.5+. + The new yaml-cpp API removes the "node >> outputvar;" operator, and + it has a new way of loading documents. There's no version hint in the + library's headers, so I'm getting the version number from pkg-config. + This part of the patch is a port of the ones created by @ktossell for + map_server and other packages. + The new yaml-cpp also does not have FindValue. +* Contributors: Scott K Logan + +0.5.2 (2013-11-05) +------------------ + +0.5.1 (2013-10-14) +------------------ +* Unify naming politics for binaries and plugins. + +0.5.0 (2013-10-11) +------------------ +* Renamed as yocs_cmd_vel_mux. + +0.4.1 (2013-10-08) +------------------ + +0.4.0 (2013-08-29) +------------------ +* Add bugtracker and repo info URLs. +* Changelogs at package level. +* License link fixed. + +0.3.0 (2013-07-02) +------------------ + +0.2.3 (2013-04-15) +------------------ + +0.2.2 (2013-02-10) +------------------ + +0.2.1 (2013-02-08) +------------------ + +0.2.0 (2013-02-07) +------------------ +* Catkinized. + +0.1.3 (2013-01-08) +------------------ +* More generous description. + +0.1.2 (2013-01-02) +------------------ +* Dynamically reconfigurable. +* Upgraded to new groovy plugin formats. +* Add reconfigure launcher and parameter file. +* Add a dynamic reconfigure script to accept a yaml filename. + +0.1.1 (2012-12-21) +------------------ + +0.1.0 (2012-12-05) +------------------ +* Initial version. diff --git a/ros2_ws/src/cmd_vel_mux/CMakeLists.txt b/ros2_ws/src/cmd_vel_mux/CMakeLists.txt new file mode 100644 index 0000000..f9cd443 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/CMakeLists.txt @@ -0,0 +1,68 @@ +cmake_minimum_required(VERSION 3.5) +project(cmd_vel_mux) + +# Default to C++14 +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 14) +endif() + +if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic) +endif() + +find_package(ament_cmake_ros REQUIRED) +find_package(geometry_msgs REQUIRED) +find_package(rcl_interfaces REQUIRED) +find_package(rclcpp REQUIRED) +find_package(rclcpp_components REQUIRED) +find_package(rcpputils REQUIRED) +find_package(std_msgs REQUIRED) + +include_directories(include) + +# Nodelet library +add_library(${PROJECT_NAME} SHARED src/cmd_vel_mux.cpp) +ament_target_dependencies(${PROJECT_NAME} + geometry_msgs + rcl_interfaces + rclcpp + rclcpp_components + rcpputils + std_msgs +) + +rclcpp_components_register_node(${PROJECT_NAME} + PLUGIN "cmd_vel_mux::CmdVelMux" + EXECUTABLE cmd_vel_mux_node) + +install(TARGETS ${PROJECT_NAME} + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin +) +install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include/${PROJECT_NAME} +) + +install(DIRECTORY config launch + DESTINATION share/${PROJECT_NAME} +) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + + find_package(ros_testing REQUIRED) + + add_ros_test(test/test_cmd_vel_mux.py + TARGET test_cmd_vel_mux + TIMEOUT 30 + ) + + add_ros_test(test/test_cmd_vel_mux_updates.py + TARGET test_cmd_vel_mux_updates + TIMEOUT 30 + ) +endif() + +ament_package() diff --git a/ros2_ws/src/cmd_vel_mux/LICENSE b/ros2_ws/src/cmd_vel_mux/LICENSE new file mode 100644 index 0000000..7c4d17d --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/LICENSE @@ -0,0 +1,31 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Yujin Robot nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. diff --git a/ros2_ws/src/cmd_vel_mux/README.md b/ros2_ws/src/cmd_vel_mux/README.md new file mode 100644 index 0000000..9710b5a --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/README.md @@ -0,0 +1,47 @@ +# cmd_vel mux + +## About + +A ROS 2 package for selecting among a number of incoming geometry_msg/msg/Twist messages, choosing the highest +priority one to republish on the output topic. It will automatically dislodge streams that are lower +priority or that stop publishing for any reason. The stream currently in use is published on the +"active" topic. + +## Published Topics +* `/active` (`std_msgs/msg/String`) - A latched topic. Publishes the "name" field of the currently active `geometry_msgs/msg/Twist` stream (see Parameters below), or "idle" if nothing is being a published. +* `/cmd_vel` (`geometry_msgs/msg/Twist`) - The current `geometry_msgs/msg/Twist` message. The values from the current highest-priority `geometry_msgs/msg/Twist` are republished here without change. + +## Subscribed Topics +* `/any` (`geometry_msgs/msg/Twist`) - For each named input (see Parameters below), a topic of type `geometry_msgs/msg/Twist` is subscribed to based on the `topic` parameter. The data from the highest-priority of these inputs is republished on the output `/cmd_vel`. + +## Parameters +The cmd_vel_mux node uses a dictionary to hold the subscribers, with `name` being the key of each element: +* `name` (string) - The "name" of each of the input `geometry_msgs/msg/Twist` topics. This is what will be published on the `active` topic when the currently active publisher changes. +* `topic` (string) - The "topic" corresponding to each of the input `geometry_msgs/msg/Twist` topics. This is what will be subscribed to. +* `timeout` (double) - The "timeout" of each of the input `geometry_msgs/msg/Twist` topics. If no data is received on the input topic for this amount of time, the input will be automatically disabled. +* `priority` (integer) - The "priority" of each of the input `geometry_msgs/msg/Twist` topics. The higher the number, the higher the priority. Higher priority topics will dislodge lower priority topics and start publishing to the output topic automatically. +* `short_desc` (string) - The "short description" of each of the input `geometry_msgs/msg/Twist` topics. This is informational only. + +See config/cmd_vel_mux_params.yaml for an example of how to set these up. + +## Changing values +The dictionary translates to parameters in the form of `subscribers.` + name + `topic/timeout/priority/short_desc`. +It can be changed on the fly using `ros2 param set` command, followed with the parameter in the form mentioned above and the value. + +## Adding subscriber +To add a new subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic, timeout, priority and short_desc. All 4 need to be present for a new subscriber to be added. + +**Ex.1** for testing: +``` +ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 4, string_value: /input/new_input}}, {name : subscribers.new_input.priority, value: {type: 2, integer_value: 20}}, {name : subscribers.new_input.timeout, value: {type: 3, double_value: 0.2}}, {name : subscribers.new_input.short_desc, value: {type: 4, string_value: 'test input'}}]}" +``` +sets *new_input* subscriber listening at topic `/input/new_input` + +## Deleting subscriber +To delete a subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic,timeout,priority and short_desc with the `type` key inside the `rcl/parameter/ParameterValue` being set to 0 (PARAMETER_NOT_SET). + +**Ex.2** for testing: +``` +ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 0}}, {name : subscribers.new_input.priority, value: {type: 0}}, {name : subscribers.new_input.timeout, value: {type: 0}}, {name : subscribers.new_input.short_desc, value: {type: 0}}]}" +``` + deletes *new_input* subscriber added at ex.1 diff --git a/ros2_ws/src/cmd_vel_mux/config/cmd_vel_mux_params.yaml b/ros2_ws/src/cmd_vel_mux/config/cmd_vel_mux_params.yaml new file mode 100644 index 0000000..43afd02 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/config/cmd_vel_mux_params.yaml @@ -0,0 +1,47 @@ +# Created on: Feb 05, 2020 +# Author: Jose Tomas Lorente +# Configuration for subscribers to cmd_vel sources. This file is provided just as an example. +# Typically automatic controllers, as ROS navigation stack should have the minimum priority +# +# Used with example.launch +# +# Individual subscriber configuration: +# name: Source name +# topic: The topic that provides cmd_vel messages +# timeout: Time in seconds without incoming messages to consider this topic inactive +# priority: Priority: an UNIQUE unsigned integer from 0 (lowest) to MAX_INT +# short_desc: Short description + +cmd_vel_mux: + ros__parameters: + subscribers: + default_input: + topic: "input/default" + timeout: 0.1 + priority: 0 + short_desc: "The default cmd_vel, controllers unaware that we are multiplexing cmd_vel should come here" + navigation_stack: + topic: "input/navigation" + timeout: 0.5 + priority: 1 + short_desc: "Navigation stack controller" + navigation_stack_controller: + topic: "input/joystick" + timeout: 0.1 + priority: 10 + short_desc: "Navigation stack remote control" + remote_control: + topic: "input/remote" + timeout: 0.1 + priority: 9 + short_desc: "Remote control" + web_application: + topic: "input/webapp" + timeout: 0.3 + priority: 8 + short_desc: "Web application" + keyboard_operation: + topic: "input/keyop" + timeout: 0.1 + priority: 7 + short_desc: "Keyboard operation" diff --git a/ros2_ws/src/cmd_vel_mux/include/cmd_vel_mux/cmd_vel_mux.hpp b/ros2_ws/src/cmd_vel_mux/include/cmd_vel_mux/cmd_vel_mux.hpp new file mode 100644 index 0000000..c69dfa3 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/include/cmd_vel_mux/cmd_vel_mux.hpp @@ -0,0 +1,152 @@ +// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos +// All rights reserved. +// +// Software License Agreement (BSD License 2.0) +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Yujin Robot nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef CMD_VEL_MUX__CMD_VEL_MUX_HPP_ +#define CMD_VEL_MUX__CMD_VEL_MUX_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include + +#include "geometry_msgs/msg/twist.hpp" +#include "rcl_interfaces/msg/set_parameters_result.hpp" +#include "rclcpp/rclcpp.hpp" +#include "std_msgs/msg/string.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace cmd_vel_mux +{ + +/***************************************************************************** + ** CmdVelMux + *****************************************************************************/ + +struct ParameterValues +{ + std::string topic; /**< The name of the topic */ + double timeout{-1.0}; /**< Timer's timeout, in seconds */ + int64_t priority{-1}; /**< UNIQUE integer from 0 (lowest priority) to MAX_INT */ + std::string short_desc; /**< Short description */ +}; + +bool operator==(const ParameterValues & parameters1, const ParameterValues & parameters2) +{ + if (parameters1.topic != parameters2.topic) { + return false; + } else if (parameters1.timeout != parameters2.timeout) { + return false; + } else if (parameters1.priority != parameters2.priority) { + return false; + } else if (parameters1.short_desc != parameters2.short_desc) { + return false; + } + return true; +} + +class CmdVelMux final : public rclcpp::Node +{ +public: + explicit CmdVelMux(rclcpp::NodeOptions options); + ~CmdVelMux() override = default; + CmdVelMux(CmdVelMux && c) = delete; + CmdVelMux & operator=(CmdVelMux && c) = delete; + CmdVelMux(const CmdVelMux & c) = delete; + CmdVelMux & operator=(const CmdVelMux & c) = delete; + +private: + /// ID for "nobody" active input + static const char * const VACANT; + + /// Multiplexed command velocity topic + rclcpp::Publisher::SharedPtr output_topic_pub_; + /// Currently allowed cmd_vel subscriber + rclcpp::Publisher::SharedPtr active_subscriber_pub_; + rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr param_cb_; + + std::string allowed_; + + void timerCallback(const std::string & key); + void cmdVelCallback( + const std::shared_ptr msg, + const std::string & key); + + rcl_interfaces::msg::SetParametersResult parameterUpdate( + const std::vector & update_parameters); + + /********************* + ** Private Classes + **********************/ + + /** + * Inner class describing an individual subscriber to a cmd_vel topic + */ + struct CmdVelSub final + { + /// Descriptive name; must be unique to this subscriber + std::string name_; + ParameterValues values_; + /// The subscriber itself + rclcpp::Subscription::SharedPtr sub_; + /// No incoming messages timeout + rclcpp::TimerBase::SharedPtr timer_; + }; + + bool addInputToParameterMap( + std::map & parsed_parameters, + const std::string & input_name, const std::string & parameter_name, + const rclcpp::Parameter & parameter_value); + bool parametersAreValid( + const std::map & parameters) const; + void configureFromParameters( + const std::map & parameters); + std::map parseFromParametersMap( + const std::map & parameters); + + std::map> map_; +}; + +} // namespace cmd_vel_mux + +#endif // CMD_VEL_MUX__CMD_VEL_MUX_HPP_ diff --git a/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-composed-launch.py b/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-composed-launch.py new file mode 100644 index 0000000..7789029 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-composed-launch.py @@ -0,0 +1,71 @@ +# Copyright 2020 Open Source Robotics Foundation, Inc. +# All rights reserved. +# +# Software License Agreement (BSD License 2.0) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of {copyright_holder} nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Launch the cmd_vel_mux node composed with default configuration.""" + +import os + +import ament_index_python.packages + +from launch import LaunchDescription +from launch_ros.actions import ComposableNodeContainer +from launch_ros.descriptions import ComposableNode + +import yaml + + +def generate_launch_description(): + share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux') + # Passing parameters to a composed node must be done via a dictionary of + # key -> value pairs. Here we read in the data from the configuration file + # and create a dictionary of it that the ComposableNode will accept. + params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml') + with open(params_file, 'r') as f: + params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters'] + + container = ComposableNodeContainer( + name='cmd_vel_mux_container', + namespace='', + package='rclcpp_components', + executable='component_container', + composable_node_descriptions=[ + ComposableNode( + package='cmd_vel_mux', + plugin='cmd_vel_mux::CmdVelMux', + name='cmd_vel_mux', + parameters=[params] + ), + ], + output='both', + ) + + return LaunchDescription([container]) diff --git a/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-launch.py b/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-launch.py new file mode 100644 index 0000000..25fc566 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/launch/cmd_vel_mux-launch.py @@ -0,0 +1,63 @@ +# Copyright 2020 Open Source Robotics Foundation, Inc. +# All rights reserved. +# +# Software License Agreement (BSD License 2.0) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of {copyright_holder} nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Launch the cmd_vel_mux node with default configuration.""" + +import os + +import ament_index_python.packages +import launch +import launch_ros.actions + +import yaml + + +def generate_launch_description(): + share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux') + # There are two different ways to pass parameters to a non-composed node; + # either by specifying the path to the file containing the parameters, or by + # passing a dictionary containing the key -> value pairs of the parameters. + # When starting a *composed* node on the other hand, only the dictionary + # style is supported. To keep the code between the non-composed and + # composed launch file similar, we use that style here as well. + params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml') + with open(params_file, 'r') as f: + params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters'] + + cmd_vel_mux_node = launch_ros.actions.Node( + package='cmd_vel_mux', + executable='cmd_vel_mux_node', + output='both', + parameters=[params] + ) + + return launch.LaunchDescription([cmd_vel_mux_node]) diff --git a/ros2_ws/src/cmd_vel_mux/package.xml b/ros2_ws/src/cmd_vel_mux/package.xml new file mode 100644 index 0000000..7674d8d --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/package.xml @@ -0,0 +1,50 @@ + + + + cmd_vel_mux + 0.12.1 + + A multiplexer for command velocity inputs. Arbitrates incoming cmd_vel messages from several topics, + allowing one topic at a time to command the robot, based on priorities. It also deallocates current + allowed topic if no messages are received after a configured timeout. All topics, together with their + priority and timeout are configured through a YAML file, that can be reload at runtime. + + Chris Lalancette + BSD + https://github.com/kobuki-base/cmd_vel_mux + https://github.com/kobuki-base/cmd_vel_mux + https://github.com/kobuki-base/cmd_vel_mux/issues + Jorge Santos Simon + Jihoon Lee + + ament_cmake_ros + + geometry_msgs + rcl_interfaces + rclcpp + rclcpp_components + rcpputils + std_msgs + + geometry_msgs + rcl_interfaces + rclcpp + rclcpp_components + rcpputils + std_msgs + + + ament_cmake_cppcheck + ament_cmake_cpplint + ament_cmake_flake8 + ament_cmake_lint_cmake + ament_cmake_pep257 + ament_cmake_uncrustify + ament_cmake_xmllint + ament_lint_auto + ros_testing + + + ament_cmake + + diff --git a/ros2_ws/src/cmd_vel_mux/src/cmd_vel_mux.cpp b/ros2_ws/src/cmd_vel_mux/src/cmd_vel_mux.cpp new file mode 100644 index 0000000..567fd5f --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/src/cmd_vel_mux.cpp @@ -0,0 +1,429 @@ +// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos +// All rights reserved. +// +// Software License Agreement (BSD License 2.0) +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Yujin Robot nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cmd_vel_mux/cmd_vel_mux.hpp" +#include "geometry_msgs/msg/twist.hpp" +#include "rcl_interfaces/msg/set_parameters_result.hpp" +#include "rclcpp/rclcpp.hpp" +#include "rclcpp_components/register_node_macro.hpp" +#include "rcpputils/split.hpp" +#include "std_msgs/msg/string.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace cmd_vel_mux +{ + +/***************************************************************************** + ** Implementation + *****************************************************************************/ +const char * const CmdVelMux::VACANT = "empty"; + +CmdVelMux::CmdVelMux(rclcpp::NodeOptions options) +: rclcpp::Node("cmd_vel_mux", options.allow_undeclared_parameters( + true).automatically_declare_parameters_from_overrides(true)), allowed_(VACANT) +{ + std::map parameters; + // Check if there are loaded parameters from config file besides sim_time_used + if (!get_parameters("subscribers", parameters) || parameters.size() < 1) { + RCLCPP_WARN(get_logger(), "No subscribers configured!"); + } else { + std::map parsed_parameters = parseFromParametersMap(parameters); + if (parsed_parameters.empty()) { + // We ran into some kind of error while configuring, quit + throw std::runtime_error("Invalid parameters"); + } + if (!parametersAreValid(parsed_parameters)) { + throw std::runtime_error("Incomplete parameters"); + } + configureFromParameters(parsed_parameters); + } + + param_cb_ = + add_on_set_parameters_callback( + std::bind(&CmdVelMux::parameterUpdate, this, std::placeholders::_1)); + + output_topic_pub_ = this->create_publisher("cmd_vel", 10); + RCLCPP_DEBUG(get_logger(), "CmdVelMux : subscribe to output topic 'cmd_vel'"); + + active_subscriber_pub_ = this->create_publisher( + "active", rclcpp::QoS(1).transient_local()); // latched topic + + // Notify the world that right now nobody is publishing on cmd_vel yet + auto active_msg = std::make_unique(); + active_msg->data = "idle"; + active_subscriber_pub_->publish(std::move(active_msg)); + + RCLCPP_DEBUG(get_logger(), "CmdVelMux : successfully initialized"); +} + +bool CmdVelMux::parametersAreValid(const std::map & parameters) const +{ + std::set used_priorities; + + for (const std::pair & parameter : parameters) { + if (parameter.second.topic.empty()) { + RCLCPP_WARN(get_logger(), "Empty topic for '%s'", parameter.first.c_str()); + return false; + } + if (parameter.second.timeout < 0.0) { + RCLCPP_WARN(get_logger(), "Missing timeout for '%s', ignoring", parameter.first.c_str()); + return false; + } + if (parameter.second.priority < 0) { + RCLCPP_WARN(get_logger(), "Missing priority for '%s', ignoring", parameter.first.c_str()); + return false; + } + if (parameter.second.short_desc.empty()) { + RCLCPP_WARN(get_logger(), "Empty short_desc for '%s', ignoring", parameter.first.c_str()); + return false; + } + + if (used_priorities.count(parameter.second.priority) != 0) { + RCLCPP_WARN(get_logger(), "Cannot have duplicate priorities, ignoring"); + return false; + } + used_priorities.insert(parameter.second.priority); + } + + return true; +} + +void CmdVelMux::configureFromParameters(const std::map & parameters) +{ + std::map> new_map; + + for (const std::pair & parameter : parameters) { + const std::string & key = parameter.first; + const ParameterValues & parameter_values = parameter.second; + // Check if parameter subscriber has all its necessary values + if (map_.count(key) != 0) { + // For names already in the subscribers map, retain current + // object so we don't re-subscribe to the topic + new_map[key] = map_[key]; + } else { + new_map[key] = std::make_shared(); + } + + // update existing or new object with the new configuration + + new_map[key]->name_ = key; + new_map[key]->values_.priority = parameter_values.priority; + new_map[key]->values_.short_desc = parameter_values.short_desc; + + if (parameter_values.topic != new_map[key]->values_.topic) { + // Shutdown the topic if the name has changed so it gets recreated + // on configuration reload. In the case of new subscribers, topic + // is empty and shutdown has just no effect + new_map[key]->values_.topic = parameter_values.topic; + new_map[key]->sub_ = nullptr; + } + + if (parameter_values.timeout != new_map[key]->values_.timeout) { + // Change timer period if the timeout changed + new_map[key]->values_.timeout = parameter_values.timeout; + new_map[key]->timer_ = nullptr; + } + } + + // Take down the deleted subscriber if it was the one being used as source + if (allowed_ != VACANT && new_map.count(allowed_) == 0) { + allowed_ = VACANT; + // ...notify the world that nobody is publishing on cmd_vel; its vacant + auto active_msg = std::make_unique(); + active_msg->data = "idle"; + active_subscriber_pub_->publish(std::move(active_msg)); + } + + map_ = new_map; + + // (Re)create subscribers whose topic is invalid: new ones and those with changed names + for (std::pair> & m : map_) { + const std::string & key = m.first; + const std::shared_ptr & values = m.second; + if (!values->sub_) { + values->sub_ = this->create_subscription( + values->values_.topic, 10, + [this, key](const geometry_msgs::msg::Twist::SharedPtr msg) {cmdVelCallback(msg, key);}); + RCLCPP_DEBUG( + get_logger(), "CmdVelMux : subscribed to '%s' on topic '%s'. pr: %" PRId64 ", to: %.2f", + values->name_.c_str(), values->values_.topic.c_str(), + values->values_.priority, values->values_.timeout); + } else { + RCLCPP_DEBUG( + get_logger(), "CmdVelMux : no need to re-subscribe to input topic '%s'", + values->values_.topic.c_str()); + } + + if (!values->timer_) { + // Create (stopped by now) a one-shot timer for every subscriber, if it doesn't exist yet + values->timer_ = this->create_wall_timer( + std::chrono::duration_cast( + std::chrono::duration( + values->values_.timeout)), [this, key]() {timerCallback(key);}); + } + } + + RCLCPP_INFO(get_logger(), "CmdVelMux : (re)configured"); +} + +bool CmdVelMux::addInputToParameterMap( + std::map & parsed_parameters, + const std::string & input_name, + const std::string & parameter_name, + const rclcpp::Parameter & parameter_value) +{ + if (parameter_name == "topic") { + std::string topic; + + if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) { + topic.clear(); + } else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) { + topic = parameter_value.as_string(); + } else { + RCLCPP_WARN(get_logger(), "topic must be a string; ignoring"); + return false; + } + + if (parsed_parameters.count(input_name) == 0) { + parsed_parameters.emplace(std::make_pair(input_name, ParameterValues())); + } + parsed_parameters[input_name].topic = topic; + } else if (parameter_name == "timeout") { + double timeout{-1.0}; + + if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) { + timeout = -1.0; + } else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE) { + timeout = parameter_value.as_double(); + } else { + RCLCPP_WARN(get_logger(), "timeout must be a double; ignoring"); + return false; + } + + if (parsed_parameters.count(input_name) == 0) { + parsed_parameters.emplace(std::make_pair(input_name, ParameterValues())); + } + parsed_parameters[input_name].timeout = timeout; + } else if (parameter_name == "priority") { + int64_t priority{-1}; + + if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) { + priority = -1; + } else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER) { + priority = parameter_value.as_int(); + if (priority < 0 || priority > std::numeric_limits::max()) { + RCLCPP_WARN(get_logger(), "Priority out of range, must be between 0 and MAX_UINT32"); + return false; + } + } else { + RCLCPP_WARN(get_logger(), "priority must be an integer; ignoring"); + return false; + } + + if (parsed_parameters.count(input_name) == 0) { + parsed_parameters.emplace(std::make_pair(input_name, ParameterValues())); + } + parsed_parameters[input_name].priority = priority; + } else if (parameter_name == "short_desc") { + std::string short_desc; + if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) { + short_desc.clear(); + } else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) { + short_desc = parameter_value.as_string(); + } else { + RCLCPP_WARN(get_logger(), "short_desc must be a string; ignoring"); + return false; + } + + if (parsed_parameters.count(input_name) == 0) { + parsed_parameters.emplace(std::make_pair(input_name, ParameterValues())); + } + parsed_parameters[input_name].short_desc = short_desc; + } else { + RCLCPP_WARN(get_logger(), "Invalid input variable '%s'; ignored", parameter_name.c_str()); + return false; + } + + return true; +} + +std::map CmdVelMux::parseFromParametersMap( + const std::map & parameters) +{ + std::map parsed_parameters; + // Iterate over all parameters and parse their content + for (const std::pair & parameter : parameters) { + std::vector splits = rcpputils::split(parameter.first, '.'); + if (splits.size() != 2) { + RCLCPP_WARN( + get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.first.c_str()); + continue; + } + + const std::string & input_name = splits[0]; + const std::string & parameter_name = splits[1]; + const rclcpp::Parameter & parameter_value = parameter.second; + if (!addInputToParameterMap(parsed_parameters, input_name, parameter_name, parameter_value)) { + parsed_parameters.clear(); + break; + } + } + + return parsed_parameters; +} + +void CmdVelMux::cmdVelCallback( + const std::shared_ptr msg, + const std::string & key) +{ + // if subscriber was deleted or the one being called right now just ignore + if (map_.count(key) == 0) { + return; + } + + // Reset timer for this source + map_[key]->timer_->reset(); + + // Give permit to publish to this source if it's the only active or is + // already allowed or has higher priority that the currently allowed + if ((allowed_ == VACANT) || + (allowed_ == key) || + (map_[key]->values_.priority > map_[allowed_]->values_.priority)) + { + if (allowed_ != key) { + allowed_ = key; + + // Notify the world that a new cmd_vel source took the control + auto active_msg = std::make_unique(); + active_msg->data = map_[key]->name_; + active_subscriber_pub_->publish(std::move(active_msg)); + } + + output_topic_pub_->publish(*msg); + } +} + +// The per-topic timerCallback is continually reset as cmd_vel messages are +// received. Thus, if it ever expires, then the topic hasn't published within +// the specified timeout period and it should be removed. +void CmdVelMux::timerCallback(const std::string & key) +{ + if (allowed_ == key) { + // No cmd_vel messages timeout happened to currently active source, so... + allowed_ = VACANT; + + // ...notify the world that nobody is publishing on cmd_vel; its vacant + auto active_msg = std::make_unique(); + active_msg->data = "idle"; + active_subscriber_pub_->publish(std::move(active_msg)); + } +} + +rcl_interfaces::msg::SetParametersResult CmdVelMux::parameterUpdate( + const std::vector & update_parameters) +{ + rcl_interfaces::msg::SetParametersResult result; + result.successful = true; + + std::map old_parameters; + if (!get_parameters("subscribers", old_parameters) || old_parameters.size() <= 1) { + result.successful = false; + result.reason = "no parameters loaded"; + return result; + } + + std::map parameters = parseFromParametersMap(old_parameters); + + // And then merge them + for (const rclcpp::Parameter & parameter : update_parameters) { + std::vector splits = rcpputils::split(parameter.get_name(), '.'); + if (splits.size() != 3) { + RCLCPP_WARN( + get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.get_name().c_str()); + result.successful = false; + result.reason = "Invalid or unknown parameter"; + break; + } + if (splits[0] != "subscribers") { + RCLCPP_WARN( + get_logger(), "Unknown parameter prefix '%s', ignoring", parameter.get_name().c_str()); + result.successful = false; + result.reason = "Unknown parameter prefix"; + break; + } + + const std::string & input_name = splits[1]; + const std::string & parameter_name = splits[2]; + + if (!addInputToParameterMap(parameters, input_name, parameter_name, parameter)) { + result.successful = false; + result.reason = "Invalid parameter"; + break; + } + } + + if (result.successful) { + if (parametersAreValid(parameters)) { + configureFromParameters(parameters); + } else { + result.successful = false; + result.reason = "Incomplete parameters"; + } + } + + return result; +} + +} // namespace cmd_vel_mux + +RCLCPP_COMPONENTS_REGISTER_NODE(cmd_vel_mux::CmdVelMux) diff --git a/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux.py b/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux.py new file mode 100644 index 0000000..c96f5c4 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux.py @@ -0,0 +1,217 @@ +# Copyright 2020 Open Source Robotics Foundation, Inc. +# All rights reserved. +# +# Software License Agreement (BSD License 2.0) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of {copyright_holder} nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import collections.abc +import contextlib +import unittest + +import geometry_msgs.msg +import launch +import launch.actions +import launch.substitutions +import launch_ros.actions +import launch_ros.substitutions +import launch_testing.actions +import launch_testing.tools +import rclpy +import rclpy.qos +import std_msgs.msg + + +def generate_test_description(): + path_to_cmd_vel_mux_params = launch.substitutions.PathJoinSubstitution([ + launch_ros.substitutions.FindPackageShare(package='cmd_vel_mux'), + 'config', + 'cmd_vel_mux_params.yaml' + ]) + return launch.LaunchDescription([ + launch_ros.actions.Node( + package='cmd_vel_mux', + executable='cmd_vel_mux_node', + parameters=[path_to_cmd_vel_mux_params], + output='screen' + ), + launch_testing.actions.ReadyToTest() + ]) + + +latching_qos_profile = rclpy.qos.QoSProfile(depth=1) +latching_qos_profile.reliability = rclpy.qos.QoSReliabilityPolicy.RELIABLE +latching_qos_profile.durability = rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL + + +class TestCmdVelMux(unittest.TestCase): + + @classmethod + def setUpClass( + cls, + launch_service, + proc_info, + proc_output + ): + rclpy.init() + cls._node = rclpy.create_node( + 'cmd_vel_mux_testing_node', start_parameter_services=False + ) + + @classmethod + def tearDownClass(cls): + cls._node.destroy_node() + rclpy.shutdown() + + @contextlib.contextmanager + def pub( + self, + message, + *, + topic, + rate, + qos_profile=None + ): + if qos_profile is None: + qos_profile = rclpy.qos.qos_profile_system_default + publisher = self._node.create_publisher(type(message), topic, qos_profile=qos_profile) + timer = self._node.create_timer(1.0 / rate, lambda *args: publisher.publish(message)) + try: + yield + finally: + self._node.destroy_timer(timer) + self._node.destroy_publisher(publisher) + + def expect( + self, + expected_sequence, + *, + topic, + message_type=None, + timeout=None, + qos_profile=None + ): + future = rclpy.task.Future() + + if not isinstance(expected_sequence, collections.abc.Sequence): + if expected_sequence is not None: + expected_sequence = [expected_sequence] + + if expected_sequence is not None and len(expected_sequence) > 0: + if message_type is None: + message_type = type(expected_sequence[0]) + sequence_types = tuple(type(message) for message in expected_sequence) + if not all(type_ == message_type for type_ in sequence_types): + raise ValueError( + f'inconsistent message types: found {sequence_types}' + f' but expected {message_type} only' + ) + + def _callback(message): + nonlocal expected_sequence + if expected_sequence[0] == message: + expected_sequence = expected_sequence[1:] + if len(expected_sequence) == 0: + future.set_result(None) + else: + if message_type is None: + raise ValueError('cannot infer message type') + + def _callback(message): + future.set_result(None) + + if qos_profile is None: + qos_profile = rclpy.qos.qos_profile_system_default + + subscription = self._node.create_subscription( + message_type, topic, _callback, qos_profile=qos_profile + ) + try: + rclpy.spin_until_future_complete(self._node, future, timeout_sec=timeout) + return ((expected_sequence is None) ^ future.done()) + finally: + self._node.destroy_subscription(subscription) + + def test_idle_mux(self): + expected_active_input = std_msgs.msg.String() + expected_active_input.data = 'idle' + self.assertTrue(self.expect( + expected_active_input, + topic='active', timeout=2, + qos_profile=latching_qos_profile + )) + self.assertTrue(self.expect( + None, topic='cmd_vel', message_type=geometry_msgs.msg.Twist, timeout=2 + )) + + def test_mux_with_single_input(self): + default_twist = geometry_msgs.msg.Twist() + default_twist.linear.x = 1.0 + with self.pub(default_twist, topic='input/default', rate=20): + expected_active_input = std_msgs.msg.String() + expected_active_input.data = 'default_input' + self.assertTrue(self.expect( + expected_active_input, + topic='active', timeout=2, + qos_profile=latching_qos_profile + )) + self.assertTrue(self.expect(default_twist, topic='cmd_vel', timeout=2)) + + def test_mux_priority_override(self): + default_twist = geometry_msgs.msg.Twist() + default_twist.linear.x = 1.0 + + joystick_twist = geometry_msgs.msg.Twist() + joystick_twist.angular.z = 1.0 + + with self.pub( + default_twist, topic='input/default', rate=20 + ), self.pub( + joystick_twist, topic='input/joystick', rate=20 + ): + expected_active_input = std_msgs.msg.String() + expected_active_input.data = 'navigation_stack_controller' + self.assertTrue(self.expect( + expected_active_input, + topic='active', timeout=2, + qos_profile=latching_qos_profile + )) + self.assertTrue(self.expect(joystick_twist, topic='cmd_vel', timeout=2)) + + def test_mux_timeout(self): + no_twist = geometry_msgs.msg.Twist() + with self.pub(no_twist, topic='input/default', rate=8): + idle_input = std_msgs.msg.String() + idle_input.data = 'idle' + default_input = std_msgs.msg.String() + default_input.data = 'default_input' + self.assertTrue(self.expect( + [idle_input, default_input, idle_input], + topic='active', timeout=5, + qos_profile=latching_qos_profile + )) diff --git a/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux_updates.py b/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux_updates.py new file mode 100644 index 0000000..93b7e32 --- /dev/null +++ b/ros2_ws/src/cmd_vel_mux/test/test_cmd_vel_mux_updates.py @@ -0,0 +1,249 @@ +# Copyright 2020 Open Source Robotics Foundation, Inc. +# All rights reserved. +# +# Software License Agreement (BSD License 2.0) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of {copyright_holder} nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import collections +import contextlib +import functools +import re +import unittest + +import launch +import launch.actions +import launch.substitutions +import launch_ros.actions +import launch_ros.substitutions +import launch_testing.actions +import launch_testing.markers +import launch_testing.tools + +import rcl_interfaces.srv +import rclpy + + +def flatten(d, prefix=None): + assert isinstance(d, collections.abc.Mapping) + + flat_d = {} + for k, v in d.items(): + if prefix is not None: + k = prefix + '.' + k + if isinstance(v, collections.abc.Mapping): + flat_d.update(flatten(v, prefix=k)) + else: + flat_d[k] = v + return flat_d + + +@launch_testing.markers.keep_alive +def generate_test_description(): + return launch.LaunchDescription([ + launch_testing.actions.ReadyToTest() + ]) + + +class TestCmdVelMux(unittest.TestCase): + + @classmethod + def setUpClass( + cls, + launch_service, + proc_info, + proc_output + ): + @contextlib.contextmanager + def launch_cmd_vel_mux_node(self, *, parameters): + cmd_vel_mux_node_action = launch_ros.actions.Node( + package='cmd_vel_mux', + executable='cmd_vel_mux_node', + name='cmd_vel_mux', + parameters=[parameters], + output='screen' + ) + with launch_testing.tools.launch_process( + launch_service, cmd_vel_mux_node_action, proc_info, proc_output + ) as node_process: + yield node_process + cls.launch_cmd_vel_mux_node = launch_cmd_vel_mux_node + + rclpy.init() + cls._node = rclpy.create_node( + 'cmd_vel_mux_testing_node', start_parameter_services=False + ) + cls._cmd_vel_mux_set_parameters_client = cls._node.create_client( + rcl_interfaces.srv.SetParametersAtomically, + '/cmd_vel_mux/set_parameters_atomically' + ) + + def update_cmd_vel_mux_params(self, *, parameters): + self.assertTrue(self._cmd_vel_mux_set_parameters_client.wait_for_service(timeout_sec=5)) + + request = rcl_interfaces.srv.SetParametersAtomically.Request() + print(flatten(parameters)) + request.parameters = [ + rclpy.Parameter(name=name, value=value).to_parameter_msg() + for name, value in flatten(parameters).items() + ] + future = self._cmd_vel_mux_set_parameters_client.call_async(request) + rclpy.spin_until_future_complete(self._node, future, timeout_sec=5.0) + self.assertTrue(future.done()) + response = future.result() + return response.result.successful, response.result.reason + + @classmethod + def tearDownClass(cls): + cls._node.destroy_client(cls._cmd_vel_mux_set_parameters_client) + cls._node.destroy_node() + rclpy.shutdown() + + def test_no_params(self): + with self.launch_cmd_vel_mux_node(parameters={}) as node_process: + self.assertTrue(node_process.wait_for_output(functools.partial( + launch_testing.tools.expect_output, expected_lines=[ + re.compile(r'.*WARN.*No subscribers configured!') + ], strict=False + ), timeout=2)) + + def test_invalid_subscriber(self): + with self.launch_cmd_vel_mux_node( + parameters={ + 'subscribers': { + 'some_invalid_subscriber': '' + } + } + ) as node_process: + self.assertTrue(node_process.wait_for_output(functools.partial( + launch_testing.tools.expect_output, expected_lines=[ + re.compile(r'.*std::runtime_error.*'), + re.compile(r'.*Invalid parameters.*') + ], strict=False + ), timeout=2)) + self.assertTrue(node_process.wait_for_shutdown(timeout=2)) + self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK) + + def test_invalid_subscriber_params(self): + with self.launch_cmd_vel_mux_node( + parameters={ + 'subscribers': { + 'some_subscriber': { + 'topic': 0 + } + } + } + ) as node_process: + self.assertTrue(node_process.wait_for_output(functools.partial( + launch_testing.tools.expect_output, expected_lines=[ + re.compile(r'.*std::runtime_error.*'), + re.compile(r'.*Invalid parameters.*') + ], strict=False + ), timeout=2)) + self.assertTrue(node_process.wait_for_shutdown(timeout=2)) + self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK) + + def test_incomplete_params(self): + with self.launch_cmd_vel_mux_node( + parameters={ + 'subscribers': { + 'some_subscriber': { + 'topic': 'some_topic', + 'priority': 0, + 'short_desc': '' + } + } + } + ) as node_process: + self.assertTrue(node_process.wait_for_output(functools.partial( + launch_testing.tools.expect_output, expected_lines=[ + re.compile(r'.*std::runtime_error.*'), + re.compile(r'.*Incomplete parameters.*'), + ], strict=False + ), timeout=2)) + self.assertTrue(node_process.wait_for_shutdown(timeout=2)) + self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK) + + def test_params_update(self): + with self.launch_cmd_vel_mux_node(parameters={ + 'subscribers': { + 'some_subscriber': { + 'topic': 'some_topic', + 'priority': 0, + 'timeout': 1.0, + 'short_desc': 'A dummy description' + } + } + }) as node_process: + self.assertTrue(node_process.wait_for_output(functools.partial( + launch_testing.tools.expect_output, expected_lines=[ + re.compile(r'.*CmdVelMux : \(re\)configured.*'), + ], strict=False + ), timeout=2)) + + ok, reason = self.update_cmd_vel_mux_params(parameters={ + 'subscribers': { + 'some_invalid_subscriber': '' + } + }) + self.assertFalse(ok) + self.assertEqual(reason, 'Invalid or unknown parameter') + + ok, reason = self.update_cmd_vel_mux_params(parameters={ + 'subscribers': { + 'another_subscriber': { + 'topic': 'another_topic', + 'priority': 0, + 'timeout': 0.1, + } + } + }) + self.assertFalse(ok) + self.assertEqual(reason, 'Incomplete parameters') + + ok, reason = self.update_cmd_vel_mux_params(parameters={ + 'subscribers': { + 'another_subscriber': { + 'topic': 0, + } + } + }) + self.assertFalse(ok) + self.assertEqual(reason, 'Invalid parameter') + + ok, _ = self.update_cmd_vel_mux_params(parameters={ + 'subscribers': { + 'another_subscriber': { + 'topic': 'another_topic', + 'priority': 1, + 'timeout': 0.1, + 'short_desc': 'Another dummy description' + } + } + }) + self.assertTrue(ok) diff --git a/ros2_ws/src/ecl_core b/ros2_ws/src/ecl_core deleted file mode 160000 index 7bcdf80..0000000 --- a/ros2_ws/src/ecl_core +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 7bcdf804237486740071011900f3f5a55a70a9cd diff --git a/ros2_ws/src/ecl_core/.gitignore b/ros2_ws/src/ecl_core/.gitignore new file mode 100644 index 0000000..ba2d0cf --- /dev/null +++ b/ros2_ws/src/ecl_core/.gitignore @@ -0,0 +1,16 @@ +# Compiled Object files +*.slo +*.lo +*.o + +# Eclipse +.settings + +# Compiled Dynamic libraries +*.so +*.dylib + +# Compiled Static libraries +*.lai +*.la +*.a diff --git a/ros2_ws/src/ecl_core/LICENSE b/ros2_ws/src/ecl_core/LICENSE new file mode 100644 index 0000000..fb746f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/LICENSE @@ -0,0 +1,32 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2022 Daniel Stonier +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + diff --git a/ros2_ws/src/ecl_core/README.md b/ros2_ws/src/ecl_core/README.md new file mode 100644 index 0000000..a4e1978 --- /dev/null +++ b/ros2_ws/src/ecl_core/README.md @@ -0,0 +1,5 @@ +ecl_core +======== + +A set of tools and interfaces extending the capabilities of c++ to provide a lightweight, +consistent interface with a focus for control programming. diff --git a/ros2_ws/src/ecl_core/ecl_command_line/.cproject b/ros2_ws/src/ecl_core/ecl_command_line/.cproject new file mode 100644 index 0000000..7f37c3b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/.cproject @@ -0,0 +1,338 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + true + true + true + + + make + + all + true + true + true + + + make + + test + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/.project b/ros2_ws/src/ecl_core/ecl_command_line/.project new file mode 100644 index 0000000..3ebec7d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/.project @@ -0,0 +1,78 @@ + + + ecl_command_line + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_command_line/CHANGELOG.rst new file mode 100644 index 0000000..7835e2b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/CHANGELOG.rst @@ -0,0 +1,12 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_command_line +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.60.8 (2014-02-10) +------------------- + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_command_line/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/CMakeLists.txt new file mode 100644 index 0000000..49fb8aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/CMakeLists.txt @@ -0,0 +1,57 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_command_line) + +############################################################################## +# Ament +############################################################################## + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_command_line/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_command_line/doxygen/mainpage.dox new file mode 100644 index 0000000..7cbe14c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/doxygen/mainpage.dox @@ -0,0 +1,111 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Provides a templatised c++ parser for handling command line arguments. + The templates provide a very flexible manner for handling any type + of input argument. + + The code for the command line parser is a simple wrapper around another + template header library called TCLAP. + Since it is relatively small, its + bundled here in the command_line subdirectory and namespaced + in a convenient manner. Licensing terms (MIT) are included in the + command_line subdirectory (also included as an install target). + + @subsection Alternatives + + A more complicated, but more flexible alternative + (it allows argument parsing from both command line and configuration + file simultaneously) is the boost::program_options library. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Interface classes + using ecl::CmdLine; + using ecl::ArgException + // Argument classes + using ecl::SwitchArg; + using ecl::ValueArg; + using ecl::MultiArg; + using ecl::UnlabeledValueArg; + using ecl::UnlabeledMultiArg; // there are more - see tclap docs + @endcode + + + Since it is a template header library, no linking is required if you are + only using these classes. + +\section usage Usage + + @subsection Initialisation + + A single object is used to parse the command line. Initialise it with + a few default properties. These will be used to automatically + generate a --help argument. + + @code + // Supply a program description, argument separator (optional) and version number (optional). + CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP."); + // CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01"); + @endcode + + @subsection ArgumentsSection Adding Arguments + + @code + // Add a boolean (flag, name, description, default) + SwitchArg debug("d","debug","Enable debugging.", false); + cmd.add(debug); + + // Add an int (flag,name,description,compulsory flag,default value,help description of the type") + ValueArg intArg("i","integer","An integer argument for testing.",false,5,"integer"); + // Not a regular option (name,description,compulsory flag,default value,help description of the type") + UnlabeledValueArg outputDirArg("output_dir","Output directory for rectified images.",true,"./rectified","string"); + + cmd.add(intArg); + @endcode + + Valid argument types include + - @ref ecl::SwitchArg "SwitchArg" : simple boolean. + - @ref ecl::ValueArg "ValueArg" : expect some value on the command line. + - @ref ecl::MultiArg "MultiArg" : permit multiple values for an argument which get stored in a vector. + - @ref ecl::MultiSwitchArg "MultiSwitchArg" : as above, but for booleans, not often used so see TCLAP for more instructions. + - @ref ecl::UnlabeledValueArg "UnlabeledValueArg" : does not use a flag (like the arguments for copy), order is important! + - @ref ecl::UnlabeledMultiArg "UnlabeledMultiArg" : reads in all remaining unlabelled args (like rm file1.txt file2.txt etc.) + + @subsection customArgumentsSection Custom Arguments + + Custom ValueArg types can be used so long as they implement the >> operator. + + @section extraHelp Further Help (TCLAP) + + Most of tclap's doxygen is generated automatically inside the ecl. For more detailed + documentation, read the manual at + tclap's home page. + +\section unitTests Unit Tests + + - src/test/command_line.cpp + +\section examples Examples + + - src/examples/command_line.cpp + +\section ChangeLog + + - May 09 : wrapper for the tclap headers written. + - May 09 : initial import of the tclap headers. + +@section Errata + + Now it's in the ros, at some point in the future I will unwind this back to the original package since it no longer needs + to be embedded in the ecl. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_command_line/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_command_line/doxygen/namespaces.dox new file mode 100644 index 0000000..b9a7cef --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/doxygen/namespaces.dox @@ -0,0 +1,22 @@ +/** + * @namespace ecl::command_line + * + * @brief Command line parsing classes. + * + * Cross-platform collection of tools for command line parsing. It has been + * built as a wrapper around the TCLAP template library. + **/ +/* + * @namespace ecl::command_line::MultiArgHelper + * + * @brief Collection of utilities and tools for multiple argument handling in tclap. + * + * Collection of utilities and tools for multiple argument handling in tclap. + */ +/* + * @namespace ecl::command_line::ValueArgHelper + * + * @brief Collection of utilities and tools for value argument handling in tclap. + * + * Collection of utilities and tools for value argument handling in tclap. + */ diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..3df1833 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(command_line) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line.hpp new file mode 100644 index 0000000..da28959 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line.hpp @@ -0,0 +1,25 @@ +/** + * @file /include/ecl/command_line.hpp + * + * @brief Parsing command line arguments. + * + * Uses a c++ library called TCLAP (MIT license) to provide command + * line parsing for the ECL. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CMD_LINE_HPP_ +#define ECL_CMD_LINE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "command_line/cmd_line.hpp" + +#endif /*ECL_CMD_LINE_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/CMakeLists.txt new file mode 100644 index 0000000..8c7a62f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +FILE(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +INSTALL(FILES ${HEADERS} DESTINATION include/ecl/command_line) diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg.hpp new file mode 100644 index 0000000..b401093 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg.hpp @@ -0,0 +1,580 @@ +/** + * @file /include/ecl/command_line/arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + + +#ifndef TCLAP_ARGUMENT_H +#define TCLAP_ARGUMENT_H + +#include +#include +#include +#include + +#include "arg_exception.hpp" +#include "visitor.hpp" +#include "cmd_line_interface.hpp" + +namespace ecl { + +/** + * @brief Virtual parent for all the different argument classes. + * + * A virtual base class that defines the essential data for all arguments. + * This class, or one of its existing children, must be subclassed to do + * anything. + */ +class Arg +{ + private: + + /** + * Indicates whether the rest of the arguments should be ignored. + */ + static bool& ignoreRestRef() { static bool ign = false; return ign; } + + /** + * The delimiter that separates an argument flag/name from the + * value. + */ + static char& delimiterRef() { static char delim = ' '; return delim; } + + protected: + + /** + * The single char flag used to identify the argument. + * This value (preceded by a dash {-}), can be used to identify + * an argument on the command line. The _flag can be blank, + * in fact this is how unlabeled args work. Unlabeled args must + * override appropriate functions to get correct handling. Note + * that the _flag does NOT include the dash as part of the flag. + */ + std::string _flag; + + /** + * A single work namd indentifying the argument. + * This value (preceded by two dashed {--}) can also be used + * to identify an argument on the command line. Note that the + * _name does NOT include the two dashes as part of the _name. The + * _name cannot be blank. + */ + std::string _name; + + /** + * Description of the argument. + */ + std::string _description; + + /** + * Indicating whether the argument is required. + */ + bool _required; + + /** + * Label to be used in usage description. Normally set to + * "required", but can be changed when necessary. + */ + std::string _requireLabel; + + /** + * Indicates whether a value is required for the argument. + * Note that the value may be required but the argument/value + * combination may not be, as specified by _required. + */ + bool _valueRequired; + + /** + * Indicates whether the argument has been set. + * Indicates that a value on the command line has matched the + * name/flag of this argument and the values have been set accordingly. + */ + bool _alreadySet; + + /** + * A pointer to a vistitor object. + * The visitor allows special handling to occur as soon as the + * argument is matched. This defaults to NULL and should not + * be used unless absolutely necessary. + */ + Visitor* _visitor; + + /** + * Whether this argument can be ignored, if desired. + */ + bool _ignoreable; + + /** + * Indicates that the arg was set as part of an XOR and not on the + * command line. + */ + bool _xorSet; + + bool _acceptsMultipleValues; + + /** + * Performs the special handling described by the Vistitor. + */ + void _checkWithVisitor() const; + + /** + * Primary constructor. YOU (yes you) should NEVER construct an Arg + * directly, this is a base class that is extended by various children + * that are meant to be used. Use SwitchArg, ValueArg, MultiArg, + * UnlabeledValueArg, or UnlabeledMultiArg instead. + * + * \param flag - The flag identifying the argument. + * \param name - The name identifying the argument. + * \param desc - The description of the argument, used in the usage. + * \param req - Whether the argument is required. + * \param valreq - Whether the a value is required for the argument. + * \param v - The visitor checked by the argument. Defaults to NULL. + */ + Arg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + bool valreq, + Visitor* v = NULL ); + + public: + /** + * Destructor. + */ + virtual ~Arg(); + + /** + * Adds this to the specified list of Args. + * \param argList - The list to add this to. + */ + virtual void addToList( std::list& argList ) const; + + /** + * Begin ignoring arguments since the "--" argument was specified. + */ + static void beginIgnoring() { ignoreRestRef() = true; } + + /** + * Whether to ignore the rest. + */ + static bool ignoreRest() { return ignoreRestRef(); } + + /** + * The delimiter that separates an argument flag/name from the + * value. + */ + static char delimiter() { return delimiterRef(); } + + /** + * The char used as a place holder when SwitchArgs are combined. + * Currently set to '*', which shouldn't cause many problems since + * *'s are expanded by most shells on the command line. + */ + static char blankChar() { return '*'; } + + /** + * The char that indicates the beginning of a flag. Currently '-'. + */ + static char flagStartChar() { return '-'; } + + /** + * The sting that indicates the beginning of a flag. Currently "-". + * Should be identical to flagStartChar. + */ + static std::string flagStartString() { return "-"; } + + /** + * The sting that indicates the beginning of a name. Currently "--". + * Should be flagStartChar twice. + */ + static std::string nameStartString() { return "--"; } + + /** + * The name used to identify the ignore rest argument. + */ + static std::string ignoreNameString() { return "ignore_rest"; } + + /** + * Sets the delimiter for all arguments. + * \param c - The character that delimits flags/names from values. + */ + static void setDelimiter( char c ) { delimiterRef() = c; } + + /** + * Pure virtual method meant to handle the parsing and value assignment + * of the string on the command line. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. What is + * passed in from main. + */ + virtual bool processArg(int *i, std::vector& args) = 0; + + /** + * Operator ==. + * Equality operator. Must be virtual to handle unlabeled args. + * \param a - The Arg to be compared to this. + */ + virtual bool operator==(const Arg& a) const; + + /** + * Returns the argument flag. + */ + const std::string& getFlag() const; + + /** + * Returns the argument name. + */ + const std::string& getName() const; + + /** + * Returns the argument description. + */ + std::string getDescription() const; + + /** + * Indicates whether the argument is required. + */ + virtual bool isRequired() const; + + /** + * Sets _required to true. This is used by the XorHandler. + * You really have no reason to ever use it. + */ + void forceRequired(); + + /** + * Sets the _alreadySet value to true. This is used by the XorHandler. + * You really have no reason to ever use it. + */ + void xorSet(); + + /** + * Indicates whether a value must be specified for argument. + */ + bool isValueRequired() const; + + /** + * Indicates whether the argument has already been set. Only true + * if the arg has been matched on the command line. + */ + bool isSet() const; + + /** + * Indicates whether the argument can be ignored, if desired. + */ + bool isIgnoreable() const; + + /** + * A method that tests whether a string matches this argument. + * This is generally called by the processArg() method. This + * method could be re-implemented by a child to change how + * arguments are specified on the command line. + * \param s - The string to be compared to the flag/name to determine + * whether the arg matches. + */ + virtual bool argMatches( const std::string& s ) const; + + /** + * Returns a simple string representation of the argument. + * Primarily for debugging. + */ + virtual std::string toString() const; + + /** + * Returns a short ID for the usage. + * \param valueId - The value used in the id. + */ + virtual std::string shortID( const std::string& valueId = "val" ) const; + + /** + * Returns a long ID for the usage. + * \param valueId - The value used in the id. + */ + virtual std::string longID( const std::string& valueId = "val" ) const; + + /** + * Trims a value off of the flag. + * \param flag - The string from which the flag and value will be + * trimmed. Contains the flag once the value has been trimmed. + * \param value - Where the value trimmed from the string will + * be stored. + */ + virtual void trimFlag( std::string& flag, std::string& value ) const; + + /** + * Checks whether a given string has blank chars, indicating that + * it is a combined SwitchArg. If so, return true, otherwise return + * false. + * \param s - string to be checked. + */ + bool _hasBlanks( const std::string& s ) const; + + /** + * Sets the requireLabel. Used by XorHandler. You shouldn't ever + * use this. + * \param s - Set the requireLabel to this value. + */ + void setRequireLabel( const std::string& s ); + + virtual bool allowMore(); + virtual bool acceptsMultipleValues(); + +}; + +/** + * Typedef of an Arg list iterator. + */ +typedef std::list::iterator ArgListIterator; + +/** + * Typedef of an Arg vector iterator. + */ +typedef std::vector::iterator ArgVectorIterator; + +/** + * Typedef of a Visitor list iterator. + */ +typedef std::list::iterator VisitorListIterator; + + +////////////////////////////////////////////////////////////////////// +//BEGIN Arg.cpp +////////////////////////////////////////////////////////////////////// + +inline Arg::Arg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + bool valreq, + Visitor* v) : + _flag(flag), + _name(name), + _description(desc), + _required(req), + _requireLabel("required"), + _valueRequired(valreq), + _alreadySet(false), + _visitor( v ), + _ignoreable(true), + _xorSet(false), + _acceptsMultipleValues(false) +{ + if ( _flag.length() > 1 ) + throw(SpecificationException( + "Argument flag can only be one character long", toString() ) ); + + if ( _name != ignoreNameString() && + ( _flag == Arg::flagStartString() || + _flag == Arg::nameStartString() || + _flag == " " ) ) + throw(SpecificationException("Argument flag cannot be either '" + + Arg::flagStartString() + "' or '" + + Arg::nameStartString() + "' or a space.", + toString() ) ); + + if ( ( _name.find( Arg::flagStartString(), 0 ) != std::string::npos ) || + ( _name.find( Arg::nameStartString(), 0 ) != std::string::npos ) || + ( _name.find( " ", 0 ) != std::string::npos ) ) + throw(SpecificationException("Argument name cannot contain either '" + + Arg::flagStartString() + "' or '" + + Arg::nameStartString() + "' or space.", + toString() ) ); + +} + +inline Arg::~Arg() { } + +inline std::string Arg::shortID( const std::string& valueId ) const +{ + std::string id = ""; + + if ( _flag != "" ) + id = Arg::flagStartString() + _flag; + else + id = Arg::nameStartString() + _name; + + std::string delim = " "; + delim[0] = Arg::delimiter(); // ugly!!! + + if ( _valueRequired ) + id += delim + "<" + valueId + ">"; + + if ( !_required ) + id = "[" + id + "]"; + + return id; +} + +inline std::string Arg::longID( const std::string& valueId ) const +{ + std::string id = ""; + + if ( _flag != "" ) + { + id += Arg::flagStartString() + _flag; + + if ( _valueRequired ) + id += " <" + valueId + ">"; + + id += ", "; + } + + id += Arg::nameStartString() + _name; + + if ( _valueRequired ) + id += " <" + valueId + ">"; + + return id; + +} + +inline bool Arg::operator==(const Arg& a) const +{ + if ( ( _flag != "" && _flag == a._flag ) || _name == a._name) + return true; + else + return false; +} + +inline std::string Arg::getDescription() const +{ + std::string desc = ""; + if ( _required ) + desc = "(" + _requireLabel + ") "; + +// if ( _valueRequired ) +// desc += "(value required) "; + + desc += _description; + return desc; +} + +inline const std::string& Arg::getFlag() const { return _flag; } + +inline const std::string& Arg::getName() const { return _name; } + +inline bool Arg::isRequired() const { return _required; } + +inline bool Arg::isValueRequired() const { return _valueRequired; } + +inline bool Arg::isSet() const +{ + if ( _alreadySet && !_xorSet ) + return true; + else + return false; +} + +inline bool Arg::isIgnoreable() const { return _ignoreable; } + +inline void Arg::setRequireLabel( const std::string& s) +{ + _requireLabel = s; +} + +inline bool Arg::argMatches( const std::string& argFlag ) const +{ + if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) || + argFlag == Arg::nameStartString() + _name ) + return true; + else + return false; +} + +inline std::string Arg::toString() const +{ + std::string s = ""; + + if ( _flag != "" ) + s += Arg::flagStartString() + _flag + " "; + + s += "(" + Arg::nameStartString() + _name + ")"; + + return s; +} + +inline void Arg::_checkWithVisitor() const +{ + if ( _visitor != NULL ) + _visitor->visit(); +} + +/** + * Implementation of trimFlag. + */ +inline void Arg::trimFlag(std::string& flag, std::string& value) const +{ + int stop = 0; + for ( int i = 0; static_cast(i) < flag.length(); i++ ) + if ( flag[i] == Arg::delimiter() ) + { + stop = i; + break; + } + + if ( stop > 1 ) + { + value = flag.substr(stop+1); + flag = flag.substr(0,stop); + } + +} + +/** + * Implementation of _hasBlanks. + */ +inline bool Arg::_hasBlanks( const std::string& s ) const +{ + for ( int i = 1; static_cast(i) < s.length(); i++ ) + if ( s[i] == Arg::blankChar() ) + return true; + + return false; +} + +inline void Arg::forceRequired() +{ + _required = true; +} + +inline void Arg::xorSet() +{ + _alreadySet = true; + _xorSet = true; +} + +/** + * Overridden by Args that need to added to the end of the list. + */ +inline void Arg::addToList( std::list& argList ) const +{ + argList.push_front( const_cast(this) ); +} + +inline bool Arg::allowMore() +{ + return false; +} + +inline bool Arg::acceptsMultipleValues() +{ + return _acceptsMultipleValues; +} + +////////////////////////////////////////////////////////////////////// +//END Arg.cpp +////////////////////////////////////////////////////////////////////// + +} // namespace ecl + +#endif + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg_exception.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg_exception.hpp new file mode 100644 index 0000000..3174b17 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/arg_exception.hpp @@ -0,0 +1,191 @@ +/** + * @file /include/ecl/command_line/arg_exception.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_ARG_EXCEPTION_H +#define TCLAP_ARG_EXCEPTION_H + +#include +#include + +namespace ecl { + + +/** + * @brief Defines the exception that is thrown whenever a command line is created and parsed. + * + * A simple class that defines an argument exception. Should be caught + * whenever a CmdLine is created and parsed. + */ +class ArgException : public std::exception +{ + public: + + /** + * Constructor. + * \param text - The text of the exception. + * \param id - The text identifying the argument source. + * \param td - Text describing the type of ArgException it is. + * of the exception. + */ + ArgException( const std::string& text = "undefined exception", + const std::string& id = "undefined", + const std::string& td = "Generic ArgException") + : std::exception(), + _errorText(text), + _argId( id ), + _typeDescription(td) + { } + + /** + * Destructor. + */ + virtual ~ArgException() throw() { } + + /** + * Returns the error text. + */ + std::string error() const { return ( _errorText ); } + + /** + * Returns the argument id. + */ + std::string argId() const + { + if ( _argId == "undefined" ) + return " "; + else + return ( "Argument: " + _argId ); + } + + /** + * Returns the arg id and error text. + */ + const char* what() const throw() + { + static std::string ex; + ex = _argId + " -- " + _errorText; + return ex.c_str(); + } + + /** + * Returns the type of the exception. Used to explain and distinguish + * between different child exceptions. + */ + std::string typeDescription() const + { + return _typeDescription; + } + + + private: + + /** + * The text of the exception message. + */ + std::string _errorText; + + /** + * The argument related to this exception. + */ + std::string _argId; + + /** + * Describes the type of the exception. Used to distinguish + * between different child exceptions. + */ + std::string _typeDescription; + +}; + +/** + * @brief Defines the exception that is thrown when an argument is improperly parsed. + * + * Thrown from within the child Arg classes when it fails to properly + * parse the argument it has been passed. + */ +class ArgParseException : public ArgException +{ + public: + /** + * Constructor. + * \param text - The text of the exception. + * \param id - The text identifying the argument source + * of the exception. + */ + ArgParseException( const std::string& text = "undefined exception", + const std::string& id = "undefined" ) + : ArgException( text, + id, + std::string( "Exception found while parsing " ) + + std::string( "the value the Arg has been passed." )) + { } +}; + +/** + * @brief Defines the exception when an argument is improperly specified. + * + * Thrown from CmdLine when the arguments on the command line are not + * properly specified, e.g. too many arguments, required argument missing, etc. + */ +class CmdLineParseException : public ArgException +{ + public: + /** + * Constructor. + * \param text - The text of the exception. + * \param id - The text identifying the argument source + * of the exception. + */ + CmdLineParseException( const std::string& text = "undefined exception", + const std::string& id = "undefined" ) + : ArgException( text, + id, + std::string( "Exception found when the values ") + + std::string( "on the command line do not meet ") + + std::string( "the requirements of the defined ") + + std::string( "Args." )) + { } +}; + +/** + * @brief Defines the exception that is thrown whenever a conflict in arguments occurs. + * + * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g. + * same flag as another Arg, same name, etc. + */ +class SpecificationException : public ArgException +{ + public: + /** + * Constructor. + * \param text - The text of the exception. + * \param id - The text identifying the argument source + * of the exception. + */ + SpecificationException( const std::string& text = "undefined exception", + const std::string& id = "undefined" ) + : ArgException( text, + id, + std::string("Exception found when an Arg object ")+ + std::string("is improperly defined by the ") + + std::string("developer." )) + { } + +}; + +} // namespace ecl + + +#endif + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line.hpp new file mode 100644 index 0000000..67ae615 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line.hpp @@ -0,0 +1,489 @@ +/** + * @file /include/ecl/command_line/cmd_line.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_CMDLINE_H +#define TCLAP_CMDLINE_H + +#include "switch_arg.hpp" +#include "multi_switch_arg.hpp" +#include "unlabeled_value_arg.hpp" +#include "unlabeled_multi_arg.hpp" + +#include "xor_handler.hpp" +#include "help_visitor.hpp" +#include "version_visitor.hpp" +#include "ignore_rest_visitor.hpp" + +#include "cmd_line_output.hpp" +#include "std_output.hpp" + +#include "constraint.hpp" +#include "values_constraint.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ecl { + +/** + * @brief Manages the command line parsing object. + * + * The base class that manages the command line definition and passes + * along the parsing to the appropriate Arg classes. + */ +class CmdLine : public CmdLineInterface +{ + protected: + + /** + * The list of arguments that will be tested against the + * command line. + */ + std::list _argList; + + /** + * The name of the program. Set to argv[0]. + */ + std::string _progName; + + /** + * A message used to describe the program. Used in the usage output. + */ + std::string _message; + + /** + * The version to be displayed with the --version switch. + */ + std::string _version; + + /** + * The number of arguments that are required to be present on + * the command line. This is set dynamically, based on the + * Args added to the CmdLine object. + */ + int _numRequired; + + /** + * The character that is used to separate the argument flag/name + * from the value. Defaults to ' ' (space). + */ + char _delimiter; + + /** + * The handler that manages xoring lists of args. + */ + XorHandler _xorHandler; + + /** + * A list of Args to be explicitly deleted when the destructor + * is called. At the moment, this only includes the three default + * Args. + */ + std::list _argDeleteOnExitList; + + /** + * A list of Visitors to be explicitly deleted when the destructor + * is called. At the moment, these are the Vistors created for the + * default Args. + */ + std::list _visitorDeleteOnExitList; + + /** + * Object that handles all output for the CmdLine. + */ + CmdLineOutput* _output; + + /** + * Checks whether a name/flag string matches entirely matches + * the Arg::blankChar. Used when multiple switches are combined + * into a single argument. + * \param s - The message to be used in the usage. + */ + bool _emptyCombined(const std::string& s); + + /** + * Perform a delete ptr; operation on ptr when this object is deleted. + */ + void deleteOnExit(Arg* ptr); + + /** + * Perform a delete ptr; operation on ptr when this object is deleted. + */ + void deleteOnExit(Visitor* ptr); + + private: + + /** + * Encapsulates the code common to the constructors (which is all + * of it). + */ + void _constructor(); + + /** + * Is set to true when a user sets the output object. We use this so + * that we don't delete objects that are created outside of this lib. + */ + bool _userSetOutput; + + /** + * Whether or not to automatically create help and version switches. + */ + bool _helpAndVersion; + + public: + + /** + * Command line constructor. Defines how the arguments will be + * parsed. + * \param message - The message to be used in the usage + * output. + * \param delimiter - The character that is used to separate + * the argument flag/name from the value. Defaults to ' ' (space). + * \param version - The version number to be used in the + * --version switch. + * \param helpAndVersion - Whether or not to create the Help and + * Version switches. Defaults to true. + */ + CmdLine(const std::string& message, + const char delimiter = ' ', + const std::string& version = "none", + bool helpAndVersion = true); + + /** + * Deletes any resources allocated by a CmdLine object. + */ + virtual ~CmdLine(); + + /** + * Adds an argument to the list of arguments to be parsed. + * \param a - Argument to be added. + */ + void add( Arg& a ); + + /** + * An alternative add. Functionally identical. + * \param a - Argument to be added. + */ + void add( Arg* a ); + + /** + * Add two Args that will be xor'd. If this method is used, add does + * not need to be called. + * \param a - Argument to be added and xor'd. + * \param b - Argument to be added and xor'd. + */ + void xorAdd( Arg& a, Arg& b ); + + /** + * Add a list of Args that will be xor'd. If this method is used, + * add does not need to be called. + * \param xors - List of Args to be added and xor'd. + */ + void xorAdd( std::vector& xors ); + + /** + * Parses the command line. + * \param argc - Number of arguments. + * \param argv - Array of arguments. + */ + void parse(int argc, char** argv); + + /** + * + */ + CmdLineOutput* getOutput(); + + /** + * + */ + void setOutput(CmdLineOutput* co); + + /** + * + */ + std::string& getVersion(); + + /** + * + */ + std::string& getProgramName(); + + /** + * + */ + std::list& getArgList(); + + /** + * + */ + XorHandler& getXorHandler(); + + /** + * + */ + char getDelimiter(); + + /** + * + */ + std::string& getMessage(); + + /** + * + */ + bool hasHelpAndVersion(); +}; + + +/////////////////////////////////////////////////////////////////////////////// +//Begin CmdLine.cpp +/////////////////////////////////////////////////////////////////////////////// + +inline CmdLine::CmdLine(const std::string& m, + char delim, + const std::string& v, + bool help ) +: _progName("not_set_yet"), + _message(m), + _version(v), + _numRequired(0), + _delimiter(delim), + _userSetOutput(false), + _helpAndVersion(help) +{ + _constructor(); +} + +inline CmdLine::~CmdLine() +{ + ArgListIterator argIter; + VisitorListIterator visIter; + + for( argIter = _argDeleteOnExitList.begin(); + argIter != _argDeleteOnExitList.end(); + ++argIter) + delete *argIter; + + for( visIter = _visitorDeleteOnExitList.begin(); + visIter != _visitorDeleteOnExitList.end(); + ++visIter) + delete *visIter; + + if ( !_userSetOutput ) + delete _output; +} + +inline void CmdLine::_constructor() +{ + _output = new StdOutput; + + Arg::setDelimiter( _delimiter ); + + Visitor* v; + + if ( _helpAndVersion ) + { + v = new HelpVisitor( this, &_output ); + SwitchArg* help = new SwitchArg("h","help", + "Displays usage information and exits.", + false, v); + add( help ); + deleteOnExit(help); + deleteOnExit(v); + + v = new VersionVisitor( this, &_output ); + SwitchArg* vers = new SwitchArg("","version", + "Displays version information and exits.", + false, v); + add( vers ); + deleteOnExit(vers); + deleteOnExit(v); + } + + v = new IgnoreRestVisitor(); + SwitchArg* ignore = new SwitchArg(Arg::flagStartString(), + Arg::ignoreNameString(), + "Ignores the rest of the labeled arguments following this flag.", + false, v); + add( ignore ); + deleteOnExit(ignore); + deleteOnExit(v); +} + +inline void CmdLine::xorAdd( std::vector& ors ) +{ + _xorHandler.add( ors ); + + for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++) + { + (*it)->forceRequired(); + (*it)->setRequireLabel( "OR required" ); + + add( *it ); + } +} + +inline void CmdLine::xorAdd( Arg& a, Arg& b ) +{ + std::vector ors; + ors.push_back( &a ); + ors.push_back( &b ); + xorAdd( ors ); +} + +inline void CmdLine::add( Arg& a ) +{ + add( &a ); +} + +inline void CmdLine::add( Arg* a ) +{ + for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) + if ( *a == *(*it) ) + throw( SpecificationException( + "Argument with same flag/name already exists!", + a->longID() ) ); + + a->addToList( _argList ); + + if ( a->isRequired() ) + _numRequired++; +} + +inline void CmdLine::parse(int argc, char** argv) +{ + try { + + _progName = argv[0]; + + // this step is necessary so that we have easy access to mutable strings. + std::vector args; + for (int i = 1; i < argc; i++) + args.push_back(argv[i]); + + int requiredCount = 0; + + for (int i = 0; static_cast(i) < args.size(); i++) + { + bool matched = false; + for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) + { + if ( (*it)->processArg( &i, args ) ) + { + requiredCount += _xorHandler.check( *it ); + matched = true; + break; + } + } + + // checks to see if the argument is an empty combined switch ... + // and if so, then we've actually matched it + if ( !matched && _emptyCombined( args[i] ) ) + matched = true; + + if ( !matched && !Arg::ignoreRest() ) + throw(CmdLineParseException("Couldn't find match for argument", + args[i])); + } + + if ( requiredCount < _numRequired ) + throw(CmdLineParseException("One or more required arguments missing!")); + + if ( requiredCount > _numRequired ) + throw(CmdLineParseException("Too many arguments!")); + + } catch ( ArgException &e ) { + _output->failure(*this, e); exit(1); + } +} + +inline bool CmdLine::_emptyCombined(const std::string& s) +{ + if ( s[0] != Arg::flagStartChar() ) + return false; + + for ( int i = 1; static_cast(i) < s.length(); i++ ) + if ( s[i] != Arg::blankChar() ) + return false; + + return true; +} + +inline void CmdLine::deleteOnExit(Arg* ptr) +{ + _argDeleteOnExitList.push_back(ptr); +} + +inline void CmdLine::deleteOnExit(Visitor* ptr) +{ + _visitorDeleteOnExitList.push_back(ptr); +} + +inline CmdLineOutput* CmdLine::getOutput() +{ + return _output; +} + +inline void CmdLine::setOutput(CmdLineOutput* co) +{ + _userSetOutput = true; + _output = co; +} + +inline std::string& CmdLine::getVersion() +{ + return _version; +} + +inline std::string& CmdLine::getProgramName() +{ + return _progName; +} + +inline std::list& CmdLine::getArgList() +{ + return _argList; +} + +inline XorHandler& CmdLine::getXorHandler() +{ + return _xorHandler; +} + +inline char CmdLine::getDelimiter() +{ + return _delimiter; +} + +inline std::string& CmdLine::getMessage() +{ + return _message; +} + +inline bool CmdLine::hasHelpAndVersion() +{ + return _helpAndVersion; +} + +/////////////////////////////////////////////////////////////////////////////// +//End CmdLine.cpp +/////////////////////////////////////////////////////////////////////////////// + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_interface.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_interface.hpp new file mode 100644 index 0000000..e5ce9a5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_interface.hpp @@ -0,0 +1,130 @@ +/** + * @file /include/ecl/command_line/cmd_line_interface.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_COMMANDLINE_INTERFACE_H +#define TCLAP_COMMANDLINE_INTERFACE_H + +#include +#include +#include +#include +#include + + +namespace ecl { + +class Arg; +class CmdLineOutput; +class XorHandler; + +/** + * @brief Managing interface for + * The base class that manages the command line definition and passes + * along the parsing to the appropriate Arg classes. + */ +class CmdLineInterface +{ + public: + + /** + * Destructor + */ + virtual ~CmdLineInterface() {} + + /** + * Adds an argument to the list of arguments to be parsed. + * \param a - Argument to be added. + */ + virtual void add( Arg& a )=0; + + /** + * An alternative add. Functionally identical. + * \param a - Argument to be added. + */ + virtual void add( Arg* a )=0; + + /** + * Add two Args that will be xor'd. + * If this method is used, add does + * not need to be called. + * \param a - Argument to be added and xor'd. + * \param b - Argument to be added and xor'd. + */ + virtual void xorAdd( Arg& a, Arg& b )=0; + + /** + * Add a list of Args that will be xor'd. If this method is used, + * add does not need to be called. + * \param xors - List of Args to be added and xor'd. + */ + virtual void xorAdd( std::vector& xors )=0; + + /** + * Parses the command line. + * \param argc - Number of arguments. + * \param argv - Array of arguments. + */ + virtual void parse(int argc, char** argv)=0; + + /** + * Returns the CmdLineOutput object. + */ + virtual CmdLineOutput* getOutput()=0; + + /** + * \param co - CmdLineOutput object that we want to use instead. + */ + virtual void setOutput(CmdLineOutput* co)=0; + + /** + * Returns the version string. + */ + virtual std::string& getVersion()=0; + + /** + * Returns the program name string. + */ + virtual std::string& getProgramName()=0; + + /** + * Returns the argList. + */ + virtual std::list& getArgList()=0; + + /** + * Returns the XorHandler. + */ + virtual XorHandler& getXorHandler()=0; + + /** + * Returns the delimiter string. + */ + virtual char getDelimiter()=0; + + /** + * Returns the message string. + */ + virtual std::string& getMessage()=0; + + /** + * Indicates whether or not the help and version switches were created + * automatically. + */ + virtual bool hasHelpAndVersion()=0; +}; + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_output.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_output.hpp new file mode 100644 index 0000000..ac6a7a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/cmd_line_output.hpp @@ -0,0 +1,69 @@ +/** + * @file /include/ecl/command_line/cmd_line_output.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_CMDLINEOUTPUT_H +#define TCLAP_CMDLINEOUTPUT_H + +#include +#include +#include +#include +#include +#include + +namespace ecl { + +class CmdLineInterface; +class ArgException; + +/** + * @brief Tclap class indirectly used by children for standardising outputs. + * + * The interface that any output object must implement. + */ +class CmdLineOutput +{ + + public: + + /** + * Virtual destructor. + */ + virtual ~CmdLineOutput() {} + + /** + * Generates some sort of output for the USAGE. + * \param c - The CmdLine object the output is generated for. + */ + virtual void usage(CmdLineInterface& c)=0; + + /** + * Generates some sort of output for the version. + * \param c - The CmdLine object the output is generated for. + */ + virtual void version(CmdLineInterface& c)=0; + + /** + * Generates some sort of output for a failure. + * \param c - The CmdLine object the output is generated for. + * \param e - The ArgException that caused the failure. + */ + virtual void failure( CmdLineInterface& c, + ArgException& e )=0; + +}; + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/constraint.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/constraint.hpp new file mode 100644 index 0000000..14cba5a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/constraint.hpp @@ -0,0 +1,65 @@ +/** + * @file /include/ecl/command_line/constraint.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_CONSTRAINT_H +#define TCLAP_CONSTRAINT_H + +#include +#include +#include +#include +#include +#include + +namespace ecl { + + +/** + * @brief Defines the interaction between an argument and a constraint. + * + * The interface that defines the interaction between the Arg and Constraint. + */ +template +class Constraint +{ + + public: + /** + * Returns a description of the Constraint. + */ + virtual std::string description() const =0; + + /** + * Returns the short ID for the Constraint. + */ + virtual std::string shortID() const =0; + + /** + * The method used to verify that the value parsed from the command + * line meets the constraint. + * \param value - The value that will be checked. + */ + virtual bool check(const T& value) const =0; + + /** + * Destructor. + * Silences warnings about Constraint being a base class with virtual + * functions but without a virtual destructor. + */ + virtual ~Constraint() { ; } +}; + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/docbook_output.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/docbook_output.hpp new file mode 100644 index 0000000..d49bf05 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/docbook_output.hpp @@ -0,0 +1,270 @@ +/** + * @file /include/ecl/command_line/docbook_output.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_DOCBOOKOUTPUT_H +#define TCLAP_DOCBOOKOUTPUT_H + +#include +#include +#include +#include +#include + +#include "cmd_line_interface.hpp" +#include "cmd_line_output.hpp" +#include "xor_handler.hpp" +#include "arg.hpp" + +namespace ecl { + +/** + * @brief TClap class used for generating docbook output. + * + * A class that generates DocBook output for usage() method for the + * given CmdLine and its Args. + */ +class DocBookOutput : public CmdLineOutput +{ + + public: + + /** + * Prints the usage to stdout. Can be overridden to + * produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + */ + virtual void usage(CmdLineInterface& c); + + /** + * Prints the version to stdout. Can be overridden + * to produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + */ + virtual void version(CmdLineInterface& c); + + /** + * Prints (to stderr) an error message, short usage + * Can be overridden to produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + * \param e - The ArgException that caused the failure. + */ + virtual void failure(CmdLineInterface& c, + ArgException& e ); + + protected: + + /** + * Substitutes the char r for string x in string s. + * \param s - The string to operate on. + * \param r - The char to replace. + * \param x - What to replace r with. + */ + void substituteSpecialChars( std::string& s, char r, std::string& x ); + void removeChar( std::string& s, char r); + + void printShortArg(Arg* it); + void printLongArg(Arg* it); +}; + + +inline void DocBookOutput::version(CmdLineInterface& _cmd) +{ + std::cout << _cmd.getVersion() << std::endl; +} + +inline void DocBookOutput::usage(CmdLineInterface& _cmd ) +{ + std::list argList = _cmd.getArgList(); + std::string progName = _cmd.getProgramName(); + std::string version = _cmd.getVersion(); + XorHandler xorHandler = _cmd.getXorHandler(); + std::vector< std::vector > xorList = xorHandler.getXorList(); + + + std::cout << "" << std::endl; + std::cout << "" << std::endl << std::endl; + + std::cout << "" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "" << std::endl; + std::cout << progName << std::endl; + std::cout << "" << std::endl; + std::cout << "1" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "" << std::endl; + std::cout << progName << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + + std::cout << "" << progName << "" << std::endl; + + // xor + for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) + { + std::cout << "" << std::endl; + for ( ArgVectorIterator it = xorList[i].begin(); + it != xorList[i].end(); it++ ) + printShortArg((*it)); + + std::cout << "" << std::endl; + } + + // rest of args + for (ArgListIterator it = argList.begin(); it != argList.end(); it++) + if ( !xorHandler.contains( (*it) ) ) + printShortArg((*it)); + + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "Description" << std::endl; + std::cout << "" << std::endl; + std::cout << _cmd.getMessage() << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "Options" << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; + // xor + for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) + { + std::cout << "" << std::endl; + size_t xlen = xorList.size() - 1; + size_t xcount = 0; + for ( ArgVectorIterator it = xorList[i].begin(); + it != xorList[i].end(); it++, xcount++ ) + { + printLongArg((*it)); + if ( xcount < xlen ) + std::cout << "OR" << std::endl; + } + + std::cout << "" << std::endl; + } + + // rest of args + for (ArgListIterator it = argList.begin(); it != argList.end(); it++) + if ( !xorHandler.contains( (*it) ) ) + printLongArg((*it)); + + std::cout << "" << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "Version" << std::endl; + std::cout << "" << std::endl; + std::cout << version << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << "" << std::endl; + +} + +inline void DocBookOutput::failure( CmdLineInterface& _cmd, + ArgException& e ) +{ + std::cout << e.what() << std::endl; +} + +inline void DocBookOutput::substituteSpecialChars( std::string& s, + char r, + std::string& x ) +{ + size_t p; + while ( (p = s.find_first_of(r)) != std::string::npos ) + { + s.erase(p,1); + s.insert(p,x); + } +} + +inline void DocBookOutput::removeChar( std::string& s, char r) +{ + size_t p; + while ( (p = s.find_first_of(r)) != std::string::npos ) + { + s.erase(p,1); + } +} + +inline void DocBookOutput::printShortArg(Arg* a) +{ + std::string lt = "<"; + std::string gt = ">"; + + std::string id = a->shortID(); + substituteSpecialChars(id,'<',lt); + substituteSpecialChars(id,'>',gt); + removeChar(id,'['); + removeChar(id,']'); + + std::string choice = "opt"; + if ( a->isRequired() ) + choice = "req"; + + std::string repeat = "norepeat"; + if ( a->acceptsMultipleValues() ) + repeat = "repeat"; + + + + std::cout << "" + << id << "" << std::endl; + +} + +inline void DocBookOutput::printLongArg(Arg* a) +{ + std::string lt = "<"; + std::string gt = ">"; + + std::string id = a->longID(); + substituteSpecialChars(id,'<',lt); + substituteSpecialChars(id,'>',gt); + removeChar(id,'['); + removeChar(id,']'); + + std::string desc = a->getDescription(); + substituteSpecialChars(desc,'<',lt); + substituteSpecialChars(desc,'>',gt); + + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << id << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; + std::cout << desc << std::endl; + std::cout << "" << std::endl; + + std::cout << "" << std::endl; +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/help_visitor.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/help_visitor.hpp new file mode 100644 index 0000000..f2f5f27 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/help_visitor.hpp @@ -0,0 +1,65 @@ +/** + * @file /include/ecl/command_line/help_visitor.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_HELP_VISITOR_H +#define TCLAP_HELP_VISITOR_H + +#include "cmd_line_interface.hpp" +#include "cmd_line_output.hpp" +#include "visitor.hpp" + +namespace ecl { + +/** + * @brief TClap class indirectly used to define the interface for visitors. + * + * A Visitor object that calls the usage method of the given CmdLineOutput + * object for the specified CmdLine object. + */ +class HelpVisitor: public Visitor +{ + protected: + + /** + * The CmdLine the output will be generated for. + */ + CmdLineInterface* _cmd; + + /** + * The output object. + */ + CmdLineOutput** _out; + + public: + + /** + * Constructor. + * \param cmd - The CmdLine the output will be generated for. + * \param out - The type of output. + */ + HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) + : Visitor(), _cmd( cmd ), _out( out ) { } + + /** + * Calls the usage method of the CmdLineOutput for the + * specified CmdLine. + */ + void visit() { (*_out)->usage(*_cmd); exit(0); } + +}; + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/ignore_rest_visitor.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/ignore_rest_visitor.hpp new file mode 100644 index 0000000..364a32d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/ignore_rest_visitor.hpp @@ -0,0 +1,48 @@ +/** + * @file /include/ecl/command_line/ignore_rest_visitor.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_IGNORE_REST_VISITOR_H +#define TCLAP_IGNORE_REST_VISITOR_H + +#include "visitor.hpp" +#include "arg.hpp" + +namespace ecl { + + +/** + * @brief TClap class indirectly used to define the interface for visitors. + * + * A Vistor that tells the CmdLine to begin ignoring arguments after + * this one is parsed. + */ +class IgnoreRestVisitor: public Visitor +{ + public: + + /** + * Constructor. + */ + IgnoreRestVisitor() : Visitor() {} + + /** + * Sets Arg::_ignoreRest. + */ + void visit() { Arg::beginIgnoring(); } +}; + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_arg.hpp new file mode 100644 index 0000000..82492af --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_arg.hpp @@ -0,0 +1,520 @@ +/** + * @file /include/ecl/command_line/multi_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_MULTIPLE_ARGUMENT_H +#define TCLAP_MULTIPLE_ARGUMENT_H + +#include +#include +#include +#include "arg.hpp" +#include "constraint.hpp" + +#define HAVE_SSTREAM + +#if defined(HAVE_SSTREAM) +#include +#elif defined(HAVE_STRSTREAM) +#include +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + +namespace ecl { + +template class MultiArg; + +namespace MultiArgHelper { + +enum Error_e { EXTRACT_FAILURE = 1000, EXTRACT_TOO_MANY }; + +/** + * @brief TClap class internally used for extracting value args. + * + * This class is used to extract a value from an argument. + * It is used because we need a special implementation to + * deal with std::string and making a specialiced function + * puts it in the T segment, thus generating link errors. + * Having a specialiced class makes the symbols weak. + * This is not pretty but I don't know how to make it + * work any other way. + */ +template +class ValueExtractor +{ + friend class MultiArg; + + private: + + /** + * Reference to the vector of values where the result of the + * extraction will be put. + */ + std::vector &_values; + + /** + * Constructor. + * \param values - Where the values extracted will be put. + */ + ValueExtractor(std::vector &values) : _values(values) {} + + /** + * Method that will attempt to parse the input stream for values + * of type T. + * \param val - Where the values parsed will be put. + */ + int extractValue( const std::string& val ) + { + T temp; + +#if defined(HAVE_SSTREAM) + std::istringstream is(val); +#elif defined(HAVE_STRSTREAM) + std::istrstream is(val.c_str()); +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + + int valuesRead = 0; + + while ( is.good() ) + { + if ( is.peek() != EOF ) + is >> temp; + else + break; + + valuesRead++; + } + + if ( is.fail() ) + return EXTRACT_FAILURE; + + if ( valuesRead > 1 ) + return EXTRACT_TOO_MANY; + + _values.push_back(temp); + + return 0; + } +}; + +/** + * @brief TClap class internally used for string handling. + * + * Specialization for string. This is necessary because istringstream + * operator>> is not able to ignore spaces... meaning -x "X Y" will only + * read 'X'... and thus the specialization. + */ +template<> +class ValueExtractor +{ + friend class MultiArg; + + private: + + /** + * Reference to the vector of strings where the result of the + * extraction will be put. + */ + std::vector &_values; + + /** + * Constructor. + * \param values - Where the strings extracted will be put. + */ + ValueExtractor(std::vector &values) : _values(values) {} + + /** + * Method that will attempt to parse the input stream for values + * of type std::string. + * \param val - Where the values parsed will be put. + */ + int extractValue( const std::string& val ) + { + _values.push_back( val ); + return 0; + } +}; + +} //namespace MultiArgHelper + +/** + * An argument that allows multiple values of type T to be specified. Very + * similar to a ValueArg, except a vector of values will be returned + * instead of just one. + */ +template +class MultiArg : public Arg +{ + protected: + + /** + * The list of values parsed from the CmdLine. + */ + std::vector _values; + + /** + * The description of type T to be used in the usage. + */ + std::string _typeDesc; + + /** + * A list of constraint on this Arg. + */ + Constraint* _constraint; + + /** + * Extracts the value from the string. + * Attempts to parse string as type T, if this fails an exception + * is thrown. + * \param val - The string to be read. + */ + void _extractValue( const std::string& val ); + + bool _allowMore; + + public: + + /** + * Constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + Visitor* v = NULL); + + /** + * Constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param parser - A CmdLine parser object to add this Arg to + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + CmdLineInterface& parser, + Visitor* v = NULL ); + + /** + * Constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + Visitor* v = NULL ); + + /** + * Constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param parser - A CmdLine parser object to add this Arg to + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + CmdLineInterface& parser, + Visitor* v = NULL ); + + /** + * Handles the processing of the argument. + * This re-implements the Arg version of this method to set the + * _value of the argument appropriately. It knows the difference + * between labeled and unlabeled. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. Passed from main(). + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Returns a vector of type T containing the values parsed from + * the command line. + */ + const std::vector& getValue(); + + /** + * Returns the a short id string. Used in the usage. + * \param val - value to be used. + */ + virtual std::string shortID(const std::string& val="val") const; + + /** + * Returns the a long id string. Used in the usage. + * \param val - value to be used. + */ + virtual std::string longID(const std::string& val="val") const; + + /** + * Once we've matched the first value, then the arg is no longer + * required. + */ + virtual bool isRequired() const; + + virtual bool allowMore(); + +}; + +template +MultiArg::MultiArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + Visitor* v) +: Arg( flag, name, desc, req, true, v ), + _typeDesc( typeDesc ), + _constraint( NULL ), + _allowMore(false) +{ + _acceptsMultipleValues = true; +} + +template +MultiArg::MultiArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + CmdLineInterface& parser, + Visitor* v) +: Arg( flag, name, desc, req, true, v ), + _typeDesc( typeDesc ), + _constraint( NULL ), + _allowMore(false) +{ + parser.add( this ); + _acceptsMultipleValues = true; +} + +/** + * + */ +template +MultiArg::MultiArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + Visitor* v) +: Arg( flag, name, desc, req, true, v ), + _typeDesc( constraint->shortID() ), + _constraint( constraint ), + _allowMore(false) +{ + _acceptsMultipleValues = true; +} + +template +MultiArg::MultiArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + CmdLineInterface& parser, + Visitor* v) +: Arg( flag, name, desc, req, true, v ), + _typeDesc( constraint->shortID() ), + _constraint( constraint ), + _allowMore(false) +{ + parser.add( this ); + _acceptsMultipleValues = true; +} + +template +const std::vector& MultiArg::getValue() { return _values; } + +template +bool MultiArg::processArg(int *i, std::vector& args) +{ + if ( _ignoreable && Arg::ignoreRest() ) + return false; + + if ( _hasBlanks( args[*i] ) ) + return false; + + std::string flag = args[*i]; + std::string value = ""; + + trimFlag( flag, value ); + + if ( argMatches( flag ) ) + { + if ( Arg::delimiter() != ' ' && value == "" ) + throw( ArgParseException( + "Couldn't find delimiter for this argument!", + toString() ) ); + + // always take the first one, regardless of start string + if ( value == "" ) + { + (*i)++; + if ( static_cast(*i) < args.size() ) + _extractValue( args[*i] ); + else + throw( ArgParseException("Missing a value for this argument!", + toString() ) ); + } + else + _extractValue( value ); + + /* + // continuing taking the args until we hit one with a start string + while ( (unsigned int)(*i)+1 < args.size() && + args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && + args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) + _extractValue( args[++(*i)] ); + */ + + _alreadySet = true; + _checkWithVisitor(); + + return true; + } + else + return false; +} + +/** + * + */ +template +std::string MultiArg::shortID(const std::string& /*val*/) const +{ + std::string id = Arg::shortID(_typeDesc) + " ... "; + + return id; +} + +/** + * + */ +template +std::string MultiArg::longID(const std::string& /*val*/) const +{ + std::string id = Arg::longID(_typeDesc) + " (accepted multiple times)"; + + return id; +} + +/** + * Once we've matched the first value, then the arg is no longer + * required. + */ +template +bool MultiArg::isRequired() const +{ + if ( _required ) + { + if ( _values.size() > 1 ) + return false; + else + return true; + } + else + return false; + +} + +template +void MultiArg::_extractValue( const std::string& val ) +{ + MultiArgHelper::ValueExtractor ve(_values); + + int err = ve.extractValue(val); + + if ( err == MultiArgHelper::EXTRACT_FAILURE ) + throw( ArgParseException("Couldn't read argument value " + "from string '" + val + "'", toString() ) ); + + if(err == MultiArgHelper::EXTRACT_TOO_MANY) + throw( ArgParseException("More than one valid value " + "parsed from string '" + val + "'", + toString() ) ); + if ( _constraint != NULL ) + if ( ! _constraint->check( _values.back() ) ) + throw( CmdLineParseException( "Value '" + val + + "' does not meet constraint: " + + _constraint->description(), + toString() ) ); +} + +template +bool MultiArg::allowMore() +{ + bool am = _allowMore; + _allowMore = true; + return am; +} + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_switch_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_switch_arg.hpp new file mode 100644 index 0000000..327a291 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/multi_switch_arg.hpp @@ -0,0 +1,192 @@ +/** + * @file /include/ecl/command_line/multi_switch_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_MULTI_SWITCH_ARG_H +#define TCLAP_MULTI_SWITCH_ARG_H + +#include +#include + +#include "switch_arg.hpp" + +namespace ecl { + +/** +* A multiple switch argument. If the switch is set on the command line, then +* the getValue method will return the number of times the switch appears. +*/ +class MultiSwitchArg : public SwitchArg +{ + protected: + + /** + * The value of the switch. + */ + int _value; + + + public: + + /** + * MultiSwitchArg constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param init - Optional. The initial/default value of this Arg. + * Defaults to 0. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiSwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + int init = 0, + Visitor* v = NULL); + + + /** + * MultiSwitchArg constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param parser - A CmdLine parser object to add this Arg to + * \param init - Optional. The initial/default value of this Arg. + * Defaults to 0. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + MultiSwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + CmdLineInterface& parser, + int init = 0, + Visitor* v = NULL); + + + /** + * Handles the processing of the argument. + * This re-implements the SwitchArg version of this method to set the + * _value of the argument appropriately. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. Passed + * in from main(). + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Returns int, the number of times the switch has been set. + */ + int getValue(); + + /** + * Returns the shortID for this Arg. + */ + std::string shortID(const std::string& val) const; + + /** + * Returns the longID for this Arg. + */ + std::string longID(const std::string& val) const; +}; + +////////////////////////////////////////////////////////////////////// +//BEGIN MultiSwitchArg.cpp +////////////////////////////////////////////////////////////////////// +inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + int init, + Visitor* v ) +: SwitchArg(flag, name, desc, false, v), +_value( init ) +{ } + +inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + CmdLineInterface& parser, + int init, + Visitor* v ) +: SwitchArg(flag, name, desc, false, v), +_value( init ) +{ + parser.add( this ); +} + +inline int MultiSwitchArg::getValue() { return _value; } + +inline bool MultiSwitchArg::processArg(int *i, std::vector& args) +{ + if ( _ignoreable && Arg::ignoreRest() ) + return false; + + if ( argMatches( args[*i] )) + { + // so the isSet() method will work + _alreadySet = true; + + // Matched argument: increment value. + ++_value; + + _checkWithVisitor(); + + return true; + } + else if ( combinedSwitchesMatch( args[*i] ) ) + { + // so the isSet() method will work + _alreadySet = true; + + // Matched argument: increment value. + ++_value; + + // Check for more in argument and increment value. + while ( combinedSwitchesMatch( args[*i] ) ) + ++_value; + + _checkWithVisitor(); + + return false; + } + else + return false; +} + +inline std::string MultiSwitchArg::shortID(const std::string& val) const +{ + std::string id = Arg::shortID() + " ... " + val; + + return id; +} + +inline std::string MultiSwitchArg::longID(const std::string& val) const +{ + std::string id = Arg::longID() + " (accepted multiple times) " + val; + + return id; +} + +////////////////////////////////////////////////////////////////////// +//END MultiSwitchArg.cpp +////////////////////////////////////////////////////////////////////// + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/optional_unlabeled_tracker.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/optional_unlabeled_tracker.hpp new file mode 100644 index 0000000..7c41215 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/optional_unlabeled_tracker.hpp @@ -0,0 +1,53 @@ +/** + * @file /include/ecl/command_line/optional_unlabeled_tracker.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H +#define TCLAP_OPTIONAL_UNLABELED_TRACKER_H + +#include + +namespace ecl { + +class OptionalUnlabeledTracker +{ + + public: + + static void check( bool req, const std::string& argName ); + + static void gotOptional() { alreadyOptionalRef() = true; } + + static bool& alreadyOptional() { return alreadyOptionalRef(); } + + private: + + static bool& alreadyOptionalRef() { static bool ct = false; return ct; } +}; + + +inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName ) +{ + if ( OptionalUnlabeledTracker::alreadyOptional() ) + throw( SpecificationException( + "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", + argName ) ); + + if ( !req ) + OptionalUnlabeledTracker::gotOptional(); +} + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/std_output.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/std_output.hpp new file mode 100644 index 0000000..9a5710b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/std_output.hpp @@ -0,0 +1,288 @@ +/** + * @file /include/ecl/command_line/std_output.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_STDCMDLINEOUTPUT_H +#define TCLAP_STDCMDLINEOUTPUT_H + +#include +#include +#include +#include +#include +#include + +#include "cmd_line_interface.hpp" +#include "cmd_line_output.hpp" +#include "xor_handler.hpp" +#include "arg.hpp" + +namespace ecl { + +/** + * @brief TClap class indirectly used to handle CmdLine arguments. + * + * A class that isolates any output from the CmdLine object so that it + * may be easily modified. + */ +class StdOutput : public CmdLineOutput +{ + + public: + + /** + * Prints the usage to stdout. Can be overridden to + * produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + */ + virtual void usage(CmdLineInterface& c); + + /** + * Prints the version to stdout. Can be overridden + * to produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + */ + virtual void version(CmdLineInterface& c); + + /** + * Prints (to stderr) an error message, short usage + * Can be overridden to produce alternative behavior. + * \param c - The CmdLine object the output is generated for. + * \param e - The ArgException that caused the failure. + */ + virtual void failure(CmdLineInterface& c, + ArgException& e ); + + protected: + + /** + * Writes a brief usage message with short args. + * \param c - The CmdLine object the output is generated for. + * \param os - The stream to write the message to. + */ + void _shortUsage( CmdLineInterface& c, std::ostream& os ) const; + + /** + * Writes a longer usage message with long and short args, + * provides descriptions and prints message. + * \param c - The CmdLine object the output is generated for. + * \param os - The stream to write the message to. + */ + void _longUsage( CmdLineInterface& c, std::ostream& os ) const; + + /** + * This function inserts line breaks and indents long strings + * according the params input. It will only break lines at spaces, + * commas and pipes. + * \param os - The stream to be printed to. + * \param s - The string to be printed. + * \param maxWidth - The maxWidth allowed for the output line. + * \param indentSpaces - The number of spaces to indent the first line. + * \param secondLineOffset - The number of spaces to indent the second + * and all subsequent lines in addition to indentSpaces. + */ + void spacePrint( std::ostream& os, + const std::string& s, + int maxWidth, + int indentSpaces, + int secondLineOffset ) const; + +}; + + +inline void StdOutput::version(CmdLineInterface& _cmd) +{ + std::string progName = _cmd.getProgramName(); + std::string interface_version = _cmd.getVersion(); + + std::cout << std::endl << progName << " version: " + << interface_version << std::endl << std::endl; +} + +inline void StdOutput::usage(CmdLineInterface& _cmd ) +{ + std::cout << std::endl << "USAGE: " << std::endl << std::endl; + + _shortUsage( _cmd, std::cout ); + + std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl; + + _longUsage( _cmd, std::cout ); + + std::cout << std::endl; + +} + +inline void StdOutput::failure( CmdLineInterface& _cmd, + ArgException& e ) +{ + std::string progName = _cmd.getProgramName(); + + std::cerr << "PARSE ERROR: " << e.argId() << std::endl + << " " << e.error() << std::endl << std::endl; + + if ( _cmd.hasHelpAndVersion() ) + { + std::cerr << "Brief USAGE: " << std::endl; + + _shortUsage( _cmd, std::cerr ); + + std::cerr << std::endl << "For complete USAGE and HELP type: " + << std::endl << " " << progName << " --help" + << std::endl << std::endl; + } + else + usage(_cmd); + +} + +inline void StdOutput::_shortUsage( CmdLineInterface& _cmd, + std::ostream& os ) const +{ + std::list argList = _cmd.getArgList(); + std::string progName = _cmd.getProgramName(); + XorHandler xorHandler = _cmd.getXorHandler(); + std::vector< std::vector > xorList = xorHandler.getXorList(); + + std::string s = progName + " "; + + // first the xor + for ( int i = 0; static_cast(i) < xorList.size(); i++ ) + { + s += " {"; + for ( ArgVectorIterator it = xorList[i].begin(); + it != xorList[i].end(); it++ ) + s += (*it)->shortID() + "|"; + + s[s.length()-1] = '}'; + } + + // then the rest + for (ArgListIterator it = argList.begin(); it != argList.end(); it++) + if ( !xorHandler.contains( (*it) ) ) + s += " " + (*it)->shortID(); + + // if the program name is too long, then adjust the second line offset + int secondLineOffset = static_cast(progName.length()) + 2; + if ( secondLineOffset > 75/2 ) + secondLineOffset = static_cast(75/2); + + spacePrint( os, s, 75, 3, secondLineOffset ); + //spacePrint( std::cout, s, 75, 3, secondLineOffset ); +} + +inline void StdOutput::_longUsage( CmdLineInterface& _cmd, + std::ostream& os ) const +{ + std::list argList = _cmd.getArgList(); + std::string message = _cmd.getMessage(); + XorHandler xorHandler = _cmd.getXorHandler(); + std::vector< std::vector > xorList = xorHandler.getXorList(); + + // first the xor + for ( int i = 0; static_cast(i) < xorList.size(); i++ ) + { + for ( ArgVectorIterator it = xorList[i].begin(); + it != xorList[i].end(); + it++ ) + { + spacePrint( os, (*it)->longID(), 75, 3, 3 ); + spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); + + if ( it+1 != xorList[i].end() ) + spacePrint(os, "-- OR --", 75, 9, 0); + } + os << std::endl << std::endl; + } + + // then the rest + for (ArgListIterator it = argList.begin(); it != argList.end(); it++) + if ( !xorHandler.contains( (*it) ) ) + { + spacePrint( os, (*it)->longID(), 75, 3, 3 ); + spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); + os << std::endl; + } + + os << std::endl; + + spacePrint( os, message, 75, 3, 0 ); +} + +inline void StdOutput::spacePrint( std::ostream& os, + const std::string& s, + int maxWidth, + int indentSpaces, + int secondLineOffset ) const +{ + int len = static_cast(s.length()); + + if ( (len + indentSpaces > maxWidth) && maxWidth > 0 ) + { + int allowedLen = maxWidth - indentSpaces; + int start = 0; + while ( start < len ) + { + // find the substring length + int stringLen = std::min( len - start, allowedLen ); + + // trim the length so it doesn't end in middle of a word + if ( stringLen == allowedLen ) + while ( s[stringLen+start] != ' ' && + s[stringLen+start] != ',' && + s[stringLen+start] != '|' && + stringLen >= 0 ) + stringLen--; + + // ok, the word is longer than the line, so just split + // wherever the line ends + if ( stringLen <= 0 ) + stringLen = allowedLen; + + // check for newlines + for ( int i = 0; i < stringLen; i++ ) + if ( s[start+i] == '\n' ) + stringLen = i+1; + + // print the indent + for ( int i = 0; i < indentSpaces; i++ ) + os << " "; + + if ( start == 0 ) + { + // handle second line offsets + indentSpaces += secondLineOffset; + + // adjust allowed len + allowedLen -= secondLineOffset; + } + + os << s.substr(start,stringLen) << std::endl; + + // so we don't start a line with a space + while ( s[stringLen+start] == ' ' && start < len ) + start++; + + start += stringLen; + } + } + else + { + for ( int i = 0; i < indentSpaces; i++ ) + os << " "; + os << s << std::endl; + } +} +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/switch_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/switch_arg.hpp new file mode 100644 index 0000000..5fd6f99 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/switch_arg.hpp @@ -0,0 +1,199 @@ +/** + * @file /include/ecl/command_line/switch_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_SWITCH_ARG_H +#define TCLAP_SWITCH_ARG_H + +#include +#include + +#include "arg.hpp" + +namespace ecl { + + +/** + * A simple switch argument. If the switch is set on the command line, then + * the getValue method will return the opposite of the default value for the + * switch. + */ +class SwitchArg : public Arg +{ + protected: + + /** + * The value of the switch. + */ + bool _value; + + public: + + /** + * SwitchArg constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param def - The default value for this Switch. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + SwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool def = false, + Visitor* v = NULL); + + + /** + * SwitchArg constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param parser - A CmdLine parser object to add this Arg to + * \param def - The default value for this Switch. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + SwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + CmdLineInterface& parser, + bool def = false, + Visitor* v = NULL); + + + /** + * Handles the processing of the argument. + * This re-implements the Arg version of this method to set the + * _value of the argument appropriately. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. Passed + * in from main(). + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Checks a string to see if any of the chars in the string + * match the flag for this Switch. + */ + bool combinedSwitchesMatch(std::string& combined); + + /** + * Returns bool, whether or not the switch has been set. + */ + bool getValue(); + +}; + +////////////////////////////////////////////////////////////////////// +//BEGIN SwitchArg.cpp +////////////////////////////////////////////////////////////////////// +inline SwitchArg::SwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool _default, + Visitor* v ) +: Arg(flag, name, desc, false, false, v), + _value( _default ) +{ } + +inline SwitchArg::SwitchArg(const std::string& flag, + const std::string& name, + const std::string& desc, + CmdLineInterface& parser, + bool _default, + Visitor* v ) +: Arg(flag, name, desc, false, false, v), + _value( _default ) +{ + parser.add( this ); +} + +inline bool SwitchArg::getValue() { return _value; } + +inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches ) +{ + // make sure this is actually a combined switch + if ( combinedSwitches[0] != Arg::flagStartString()[0] ) + return false; + + // make sure it isn't a long name + if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == + Arg::nameStartString() ) + return false; + + // ok, we're not specifying a ValueArg, so we know that we have + // a combined switch list. + for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) + if ( combinedSwitches[i] == _flag[0] ) + { + // update the combined switches so this one is no longer present + // this is necessary so that no unlabeled args are matched + // later in the processing. + //combinedSwitches.erase(i,1); + combinedSwitches[i] = Arg::blankChar(); + return true; + } + + // none of the switches passed in the list match. + return false; +} + + +inline bool SwitchArg::processArg(int *i, std::vector& args) +{ + if ( _ignoreable && Arg::ignoreRest() ) + return false; + + if ( argMatches( args[*i] ) || combinedSwitchesMatch( args[*i] ) ) + { + // If we match on a combined switch, then we want to return false + // so that other switches in the combination will also have a + // chance to match. + bool ret = false; + if ( argMatches( args[*i] ) ) + ret = true; + + if ( _alreadySet || ( !ret && combinedSwitchesMatch( args[*i] ) ) ) + throw(CmdLineParseException("Argument already set!", toString())); + + _alreadySet = true; + + if ( _value == true ) + _value = false; + else + _value = true; + + _checkWithVisitor(); + + return ret; + } + else + return false; +} + +////////////////////////////////////////////////////////////////////// +//End SwitchArg.cpp +////////////////////////////////////////////////////////////////////// + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_multi_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_multi_arg.hpp new file mode 100644 index 0000000..74c351a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_multi_arg.hpp @@ -0,0 +1,295 @@ +/** + * @file /include/ecl/command_line/unlabeled_multi_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H +#define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H + +#include +#include + +#include "multi_arg.hpp" +#include "optional_unlabeled_tracker.hpp" + +namespace ecl { + +/** + * Just like a MultiArg, except that the arguments are unlabeled. Basically, + * this Arg will slurp up everything that hasn't been matched to another + * Arg. + */ +template +class UnlabeledMultiArg : public MultiArg +{ + + // If compiler has two stage name lookup (as gcc >= 3.4 does) + // this is requried to prevent undef. symbols + using MultiArg::_ignoreable; + using MultiArg::_hasBlanks; + using MultiArg::_extractValue; + using MultiArg::_typeDesc; + using MultiArg::_name; + using MultiArg::_description; + using MultiArg::_alreadySet; + using MultiArg::toString; + + public: + + /** + * Constructor. + * \param name - The name of the Arg. Note that this is used for + * identification, not as a long flag. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param ignoreable - Whether or not this argument can be ignored + * using the "--" flag. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + UnlabeledMultiArg( const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + bool ignoreable = false, + Visitor* v = NULL ); + /** + * Constructor. + * \param name - The name of the Arg. Note that this is used for + * identification, not as a long flag. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param parser - A CmdLine parser object to add this Arg to + * \param ignoreable - Whether or not this argument can be ignored + * using the "--" flag. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + UnlabeledMultiArg( const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + CmdLineInterface& parser, + bool ignoreable = false, + Visitor* v = NULL ); + + /** + * Constructor. + * \param name - The name of the Arg. Note that this is used for + * identification, not as a long flag. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param ignoreable - Whether or not this argument can be ignored + * using the "--" flag. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + UnlabeledMultiArg( const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + bool ignoreable = false, + Visitor* v = NULL ); + + /** + * Constructor. + * \param name - The name of the Arg. Note that this is used for + * identification, not as a long flag. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param parser - A CmdLine parser object to add this Arg to + * \param ignoreable - Whether or not this argument can be ignored + * using the "--" flag. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + UnlabeledMultiArg( const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + CmdLineInterface& parser, + bool ignoreable = false, + Visitor* v = NULL ); + + /** + * Handles the processing of the argument. + * This re-implements the Arg version of this method to set the + * _value of the argument appropriately. It knows the difference + * between labeled and unlabeled. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. Passed from main(). + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Returns the a short id string. Used in the usage. + * \param val - value to be used. + */ + virtual std::string shortID(const std::string& val="val") const; + + /** + * Returns the a long id string. Used in the usage. + * \param val - value to be used. + */ + virtual std::string longID(const std::string& val="val") const; + + /** + * Opertor ==. + * \param a - The Arg to be compared to this. + */ + virtual bool operator==(const Arg& a) const; + + /** + * Pushes this to back of list rather than front. + * \param argList - The list this should be added to. + */ + virtual void addToList( std::list& argList ) const; +}; + +template +UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + bool ignoreable, + Visitor* v) +: MultiArg("", name, desc, req, typeDesc, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(true, toString()); +} + +template +UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, + const std::string& desc, + bool req, + const std::string& typeDesc, + CmdLineInterface& parser, + bool ignoreable, + Visitor* v) +: MultiArg("", name, desc, req, typeDesc, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(true, toString()); + parser.add( this ); +} + + +template +UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + bool ignoreable, + Visitor* v) +: MultiArg("", name, desc, req, constraint, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(true, toString()); +} + +template +UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, + const std::string& desc, + bool req, + Constraint* constraint, + CmdLineInterface& parser, + bool ignoreable, + Visitor* v) +: MultiArg("", name, desc, req, constraint, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(true, toString()); + parser.add( this ); +} + + +template +bool UnlabeledMultiArg::processArg(int *i, std::vector& args) +{ + + if ( _hasBlanks( args[*i] ) ) + return false; + + // never ignore an unlabeled multi arg + + + // always take the first value, regardless of the start string + _extractValue( args[(*i)] ); + + /* + // continue taking args until we hit the end or a start string + while ( (unsigned int)(*i)+1 < args.size() && + args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && + args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) + _extractValue( args[++(*i)] ); + */ + + _alreadySet = true; + + return true; +} + +template +std::string UnlabeledMultiArg::shortID(const std::string& /*val*/) const +{ + std::string id = "<" + _typeDesc + "> ..."; + + return id; +} + +template +std::string UnlabeledMultiArg::longID(const std::string& /*val*/) const +{ + std::string id = "<" + _typeDesc + "> (accepted multiple times)"; + + return id; +} + +template +bool UnlabeledMultiArg::operator==(const Arg& a) const +{ + if ( _name == a.getName() || _description == a.getDescription() ) + return true; + else + return false; +} + +template +void UnlabeledMultiArg::addToList( std::list& argList ) const +{ + argList.push_back( const_cast(static_cast(this)) ); +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_value_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_value_arg.hpp new file mode 100644 index 0000000..2970f62 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/unlabeled_value_arg.hpp @@ -0,0 +1,335 @@ +/** + * @file /include/ecl/command_line/unlabeled_value_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H +#define TCLAP_UNLABELED_VALUE_ARGUMENT_H + +#include +#include + +#include "value_arg.hpp" +#include "optional_unlabeled_tracker.hpp" + + +namespace ecl { + +/** + * The basic unlabeled argument that parses a value. + * This is a template class, which means the type T defines the type + * that a given object will attempt to parse when an UnlabeledValueArg + * is reached in the list of args that the CmdLine iterates over. + */ +template +class UnlabeledValueArg : public ValueArg +{ + + // If compiler has two stage name lookup (as gcc >= 3.4 does) + // this is requried to prevent undef. symbols + using ValueArg::_ignoreable; + using ValueArg::_hasBlanks; + using ValueArg::_extractValue; + using ValueArg::_typeDesc; + using ValueArg::_name; + using ValueArg::_description; + using ValueArg::_alreadySet; + using ValueArg::toString; + + public: + + /** + * UnlabeledValueArg constructor. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param ignoreable - Allows you to specify that this argument can be + * ignored if the '--' flag is set. This defaults to false (cannot + * be ignored) and should generally stay that way unless you have + * some special need for certain arguments to be ignored. + * \param v - Optional Vistor. You should leave this blank unless + * you have a very good reason. + */ + UnlabeledValueArg( const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + bool ignoreable = false, + Visitor* v = NULL); + + /** + * UnlabeledValueArg constructor. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param parser - A CmdLine parser object to add this Arg to + * \param ignoreable - Allows you to specify that this argument can be + * ignored if the '--' flag is set. This defaults to false (cannot + * be ignored) and should generally stay that way unless you have + * some special need for certain arguments to be ignored. + * \param v - Optional Vistor. You should leave this blank unless + * you have a very good reason. + */ + UnlabeledValueArg( const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + CmdLineInterface& parser, + bool ignoreable = false, + Visitor* v = NULL ); + + /** + * UnlabeledValueArg constructor. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param ignoreable - Allows you to specify that this argument can be + * ignored if the '--' flag is set. This defaults to false (cannot + * be ignored) and should generally stay that way unless you have + * some special need for certain arguments to be ignored. + * \param v - Optional Vistor. You should leave this blank unless + * you have a very good reason. + */ + UnlabeledValueArg( const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + bool ignoreable = false, + Visitor* v = NULL ); + + + /** + * UnlabeledValueArg constructor. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param parser - A CmdLine parser object to add this Arg to + * \param ignoreable - Allows you to specify that this argument can be + * ignored if the '--' flag is set. This defaults to false (cannot + * be ignored) and should generally stay that way unless you have + * some special need for certain arguments to be ignored. + * \param v - Optional Vistor. You should leave this blank unless + * you have a very good reason. + */ + UnlabeledValueArg( const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + CmdLineInterface& parser, + bool ignoreable = false, + Visitor* v = NULL); + + /** + * Handles the processing of the argument. + * This re-implements the Arg version of this method to set the + * _value of the argument appropriately. Handling specific to + * unlabled arguments. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Overrides shortID for specific behavior. + */ + virtual std::string shortID(const std::string& val="val") const; + + /** + * Overrides longID for specific behavior. + */ + virtual std::string longID(const std::string& val="val") const; + + /** + * Overrides operator== for specific behavior. + */ + virtual bool operator==(const Arg& a ) const; + + /** + * Instead of pushing to the front of list, push to the back. + * \param argList - The list to add this to. + */ + virtual void addToList( std::list& argList ) const; + +}; + +/** + * Constructor implemenation. + */ +template +UnlabeledValueArg::UnlabeledValueArg(const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + bool ignoreable, + Visitor* v) +: ValueArg("", name, desc, req, value, typeDesc, v) +{ + _ignoreable = ignoreable; + + OptionalUnlabeledTracker::check(req, toString()); + +} + +template +UnlabeledValueArg::UnlabeledValueArg(const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + CmdLineInterface& parser, + bool ignoreable, + Visitor* v) +: ValueArg("", name, desc, req, value, typeDesc, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(req, toString()); + parser.add( this ); +} + +/** + * Constructor implemenation. + */ +template +UnlabeledValueArg::UnlabeledValueArg(const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + bool ignoreable, + Visitor* v) +: ValueArg("", name, desc, req, value, constraint, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(req, toString()); +} + +template +UnlabeledValueArg::UnlabeledValueArg(const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + CmdLineInterface& parser, + bool ignoreable, + Visitor* v) +: ValueArg("", name, desc, req, value, constraint, v) +{ + _ignoreable = ignoreable; + OptionalUnlabeledTracker::check(req, toString()); + parser.add( this ); +} + +/** + * Implementation of processArg(). + */ +template +bool UnlabeledValueArg::processArg(int *i, std::vector& args) +{ + + if ( _alreadySet ) + return false; + + if ( _hasBlanks( args[*i] ) ) + return false; + + // never ignore an unlabeled arg + + _extractValue( args[*i] ); + _alreadySet = true; + return true; +} + +/** + * Overriding shortID for specific output. + */ +template +std::string UnlabeledValueArg::shortID(const std::string& val) const +{ + (void)val; + std::string id = "<" + _typeDesc + ">"; + + return id; +} + +/** + * Overriding longID for specific output. + */ +template +std::string UnlabeledValueArg::longID(const std::string& val) const +{ + (void)val; + // Ideally we would like to be able to use RTTI to return the name + // of the type required for this argument. However, g++ at least, + // doesn't appear to return terribly useful "names" of the types. + std::string id = "<" + _typeDesc + ">"; + + return id; +} + +/** + * Overriding operator== for specific behavior. + */ +template +bool UnlabeledValueArg::operator==(const Arg& a ) const +{ + if ( _name == a.getName() || _description == a.getDescription() ) + return true; + else + return false; +} + +template +void UnlabeledValueArg::addToList( std::list& argList ) const +{ + argList.push_back( const_cast(static_cast(this)) ); +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/value_arg.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/value_arg.hpp new file mode 100644 index 0000000..0aedd35 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/value_arg.hpp @@ -0,0 +1,512 @@ +/** + * @file /include/ecl/command_line/value_arg.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_VALUE_ARGUMENT_H +#define TCLAP_VALUE_ARGUMENT_H + +#include +#include +#include +#include "arg.hpp" +#include "constraint.hpp" + +#define HAVE_SSTREAM + +#if defined(HAVE_SSTREAM) +#include +#elif defined(HAVE_STRSTREAM) +#include +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + +namespace ecl { + +template class ValueArg; + +namespace ValueArgHelper { + +enum Error_e { EXTRACT_FAILURE = 1000, EXTRACT_TOO_MANY }; + +/** + * @brief TClap class internally used for extracting value args. + * + * This class is used to extract a value from an argument. + * It is used because we need a special implementation to + * deal with std::string and making a specialised function + * puts it in the T segment, thus generating link errors. + * Having a specialised class makes the symbols weak. + * This is not pretty but I don't know how to make it + * work any other way. + */ +template class ValueExtractor +{ + friend class ValueArg; + + private: + + /** + * Reference to the value where the result of the extraction will + * be put. + */ + T &_value; + + /** + * Constructor. + * \param value - Where the value extracted will be put. + */ + ValueExtractor(T &value) : _value(value) { } + + /** + * Method that will attempt to parse the input stream for a value + * of type T. + * \param val - Where the value parsed will be put. + */ + int extractValue( const std::string& val ) + { + +#if defined(HAVE_SSTREAM) + std::istringstream is(val); +#elif defined(HAVE_STRSTREAM) + std::istrstream is(val.c_str()); +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + + int valuesRead = 0; + while ( is.good() ) + { + if ( is.peek() != EOF ) + is >> _value; + else + break; + + valuesRead++; + } + + if ( is.fail() ) + return EXTRACT_FAILURE; + + if ( valuesRead > 1 ) + return EXTRACT_TOO_MANY; + + return 0; + } +}; + +/** + * @brief TClap class internally used for string handling. + * + * Specialization for string. This is necessary because istringstream + * operator>> is not able to ignore spaces... meaning -x "X Y" will only + * read 'X'... and thus the specialization. + */ +template<> class ValueExtractor +{ + friend class ValueArg; + + private: + + /** + * Reference to the value where the result of the extraction will + * be put. + */ + std::string &_value; + + /** + * Constructor. + * \param value - Where the value extracted will be put. + */ + ValueExtractor(std::string &value) : _value(value) {} + + /** + * Method that will attempt to parse the input stream for a value + * of type std::string. + * \param val - Where the string parsed will be put. + */ + int extractValue( const std::string& val ) + { + _value = val; + return 0; + } +}; + +} //namespace ValueArgHelper + +/** + * The basic labeled argument that parses a value. + * This is a template class, which means the type T defines the type + * that a given object will attempt to parse when the flag/name is matched + * on the command line. While there is nothing stopping you from creating + * an unflagged ValueArg, it is unwise and would cause significant problems. + * Instead use an UnlabeledValueArg. + */ +template +class ValueArg : public Arg +{ + protected: + + /** + * The value parsed from the command line. + * Can be of any type, as long as the >> operator for the type + * is defined. + */ + T _value; + + /** + * A human readable description of the type to be parsed. + * This is a hack, plain and simple. Ideally we would use RTTI to + * return the name of type T, but until there is some sort of + * consistent support for human readable names, we are left to our + * own devices. + */ + std::string _typeDesc; + + /** + * A Constraint this Arg must conform to. + */ + Constraint* _constraint; + + /** + * Extracts the value from the string. + * Attempts to parse string as type T, if this fails an exception + * is thrown. + * \param val - value to be parsed. + */ + void _extractValue( const std::string& val ); + + public: + + /** + * Labeled ValueArg constructor. + * You could conceivably call this constructor with a blank flag, + * but that would make you a bad person. It would also cause + * an exception to be thrown. If you want an unlabeled argument, + * use the other constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + ValueArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + Visitor* v = NULL); + + + /** + * Labeled ValueArg constructor. + * You could conceivably call this constructor with a blank flag, + * but that would make you a bad person. It would also cause + * an exception to be thrown. If you want an unlabeled argument, + * use the other constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param typeDesc - A short, human readable description of the + * type that this object expects. This is used in the generation + * of the USAGE statement. The goal is to be helpful to the end user + * of the program. + * \param parser - A CmdLine parser object to add this Arg to + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + ValueArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + CmdLineInterface& parser, + Visitor* v = NULL ); + + /** + * Labeled ValueArg constructor. + * You could conceivably call this constructor with a blank flag, + * but that would make you a bad person. It would also cause + * an exception to be thrown. If you want an unlabeled argument, + * use the other constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param parser - A CmdLine parser object to add this Arg to. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + ValueArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + CmdLineInterface& parser, + Visitor* v = NULL ); + + /** + * Labeled ValueArg constructor. + * You could conceivably call this constructor with a blank flag, + * but that would make you a bad person. It would also cause + * an exception to be thrown. If you want an unlabeled argument, + * use the other constructor. + * \param flag - The one character flag that identifies this + * argument on the command line. + * \param name - A one word name for the argument. Can be + * used as a long flag on the command line. + * \param desc - A description of what the argument is for or + * does. + * \param req - Whether the argument is required on the command + * line. + * \param value - The default value assigned to this argument if it + * is not present on the command line. + * \param constraint - A pointer to a Constraint object used + * to constrain this Arg. + * \param v - An optional visitor. You probably should not + * use this unless you have a very good reason. + */ + ValueArg( const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T value, + Constraint* constraint, + Visitor* v = NULL ); + + /** + * Handles the processing of the argument. + * This re-implements the Arg version of this method to set the + * _value of the argument appropriately. It knows the difference + * between labeled and unlabeled. + * \param i - Pointer the the current argument in the list. + * \param args - Mutable list of strings. Passed + * in from main(). + */ + virtual bool processArg(int* i, std::vector& args); + + /** + * Returns the value of the argument. + */ + T& getValue() ; + + /** + * Specialization of shortID. + * \param val - value to be used. + */ + virtual std::string shortID(const std::string& val = "val") const; + + /** + * Specialization of longID. + * \param val - value to be used. + */ + virtual std::string longID(const std::string& val = "val") const; + +}; + + +/** + * Constructor implementation. + */ +template +ValueArg::ValueArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T value, + const std::string& typeDesc, + Visitor* v) +: Arg(flag, name, desc, req, true, v), + _value( value ), + _typeDesc( typeDesc ), + _constraint( NULL ) +{ } + +template +ValueArg::ValueArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T val, + const std::string& typeDesc, + CmdLineInterface& parser, + Visitor* v) +: Arg(flag, name, desc, req, true, v), + _value( val ), + _typeDesc( typeDesc ), + _constraint( NULL ) +{ + parser.add( this ); +} + +template +ValueArg::ValueArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T val, + Constraint* constraint, + Visitor* v) +: Arg(flag, name, desc, req, true, v), + _value( val ), + _typeDesc( constraint->shortID() ), + _constraint( constraint ) +{ } + +template +ValueArg::ValueArg(const std::string& flag, + const std::string& name, + const std::string& desc, + bool req, + T val, + Constraint* constraint, + CmdLineInterface& parser, + Visitor* v) +: Arg(flag, name, desc, req, true, v), + _value( val ), + _typeDesc( constraint->shortID() ), + _constraint( constraint ) +{ + parser.add( this ); +} + + +/** + * Implementation of getValue(). + */ +template +T& ValueArg::getValue() { return _value; } + +/** + * Implementation of processArg(). + */ +template +bool ValueArg::processArg(int *i, std::vector& args) +{ + if ( _ignoreable && Arg::ignoreRest() ) + return false; + + if ( _hasBlanks( args[*i] ) ) + return false; + + std::string flag = args[*i]; + + std::string value = ""; + trimFlag( flag, value ); + + if ( argMatches( flag ) ) + { + if ( _alreadySet ) + throw( CmdLineParseException("Argument already set!", toString()) ); + + if ( Arg::delimiter() != ' ' && value == "" ) + throw( ArgParseException( + "Couldn't find delimiter for this argument!", + toString() ) ); + + if ( value == "" ) + { + (*i)++; + if ( static_cast(*i) < args.size() ) + _extractValue( args[*i] ); + else + throw( ArgParseException("Missing a value for this argument!", + toString() ) ); + } + else + _extractValue( value ); + + _alreadySet = true; + _checkWithVisitor(); + return true; + } + else + return false; +} + +/** + * Implementation of shortID. + */ +template +std::string ValueArg::shortID(const std::string& val) const +{ + std::string stop_warnings = val; // Only to stop annoying warning messages, I dont think it slows things down + return Arg::shortID( _typeDesc ); +} + +/** + * Implementation of longID. + */ +template +std::string ValueArg::longID(const std::string& val) const +{ + std::string stop_warnings = val; // Only to stop annoying warning messages, I dont think it slows things down + return Arg::longID( _typeDesc ); +} + +template // Just to stop the warnings. +void ValueArg::_extractValue( const std::string& val ) +{ + ValueArgHelper::ValueExtractor ve(_value); + + int err = ve.extractValue(val); + + if ( err == ValueArgHelper::EXTRACT_FAILURE ) + throw( ArgParseException("Couldn't read argument value from string '" + + val + "'", toString() ) ); + + if ( err == ValueArgHelper::EXTRACT_TOO_MANY ) + throw( ArgParseException( + "More than one valid value parsed from string '" + + val + "'", toString() ) ); + + if ( _constraint != NULL ) + if ( ! _constraint->check( _value ) ) + throw( CmdLineParseException( "Value '" + val + + "' does not meet constraint: " + + _constraint->description(), + toString() ) ); +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/values_constraint.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/values_constraint.hpp new file mode 100644 index 0000000..6596892 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/values_constraint.hpp @@ -0,0 +1,135 @@ +/** + * @file /include/ecl/command_line/values_constraint.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_VALUESCONSTRAINT_H +#define TCLAP_VALUESCONSTRAINT_H + +#include +#include +#include "constraint.hpp" + +#define HAVE_SSTREAM + +#if defined(HAVE_SSTREAM) +#include +#elif defined(HAVE_STRSTREAM) +#include +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + +namespace ecl { + +/** + * A Constraint that constrains the Arg to only those values specified + * in the constraint. + */ +template +class ValuesConstraint : public Constraint +{ + + public: + + /** + * Constructor. + * \param allowed - vector of allowed values. + */ + ValuesConstraint(std::vector& allowed); + + /** + * Virtual destructor. + */ + virtual ~ValuesConstraint() {} + + /** + * Returns a description of the Constraint. + */ + virtual std::string description() const; + + /** + * Returns the short ID for the Constraint. + */ + virtual std::string shortID() const; + + /** + * The method used to verify that the value parsed from the command + * line meets the constraint. + * \param value - The value that will be checked. + */ + virtual bool check(const T& value) const; + + protected: + + /** + * The list of valid values. + */ + std::vector _allowed; + + /** + * The string used to describe the allowed values of this constraint. + */ + std::string _typeDesc; + +}; + +template +ValuesConstraint::ValuesConstraint(std::vector& allowed) +: _allowed(allowed) +{ + for ( unsigned int i = 0; i < _allowed.size(); i++ ) + { + +#if defined(HAVE_SSTREAM) + std::ostringstream os; +#elif defined(HAVE_STRSTREAM) + std::ostrstream os; +#else +#error "Need a stringstream (sstream or strstream) to compile!" +#endif + + os << _allowed[i]; + + std::string temp( os.str() ); + + if ( i > 0 ) + _typeDesc += "|"; + _typeDesc += temp; + } +} + +template +bool ValuesConstraint::check( const T& val ) const +{ + if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() ) + return false; + else + return true; +} + +template +std::string ValuesConstraint::shortID() const +{ + return _typeDesc; +} + +template +std::string ValuesConstraint::description() const +{ + return _typeDesc; +} + +} // namespace ecl + +#endif + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/version_visitor.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/version_visitor.hpp new file mode 100644 index 0000000..87b57d6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/version_visitor.hpp @@ -0,0 +1,65 @@ +/** + * @file /include/ecl/command_line/version_visitor.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_VERSION_VISITOR_H +#define TCLAP_VERSION_VISITOR_H + +#include "cmd_line_interface.hpp" +#include "cmd_line_output.hpp" +#include "visitor.hpp" + +namespace ecl { + +/** + * @brief TClap class indirectly used to define the interface for visitors. + * + * A Vistor that will call the version method of the given CmdLineOutput + * for the specified CmdLine object and then exit. + */ +class VersionVisitor: public Visitor +{ + protected: + + /** + * The CmdLine of interest. + */ + CmdLineInterface* _cmd; + + /** + * The output object. + */ + CmdLineOutput** _out; + + public: + + /** + * Constructor. + * \param cmd - The CmdLine the output is generated for. + * \param out - The type of output. + */ + VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) + : Visitor(), _cmd( cmd ), _out( out ) { } + + /** + * Calls the version method of the output object using the + * specified CmdLine. + */ + void visit() { (*_out)->version(*_cmd); exit(0); } + +}; + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/visitor.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/visitor.hpp new file mode 100644 index 0000000..e58dd5e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/visitor.hpp @@ -0,0 +1,47 @@ +/** + * @file /include/ecl/command_line/visitor.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_VISITOR_H +#define TCLAP_VISITOR_H + +namespace ecl { + +/** + * @brief TClap class indirectly used to define the interface for visitors. + * + * A base class that defines the interface for visitors. + */ +class Visitor +{ + public: + + /** + * Constructor. Does nothing. + */ + Visitor() { } + + /** + * Destructor. Does nothing. + */ + virtual ~Visitor() { } + + /** + * Does nothing. Should be overridden by child. + */ + virtual void visit() { } +}; +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/xor_handler.hpp b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/xor_handler.hpp new file mode 100644 index 0000000..8ab3e0a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/include/ecl/command_line/xor_handler.hpp @@ -0,0 +1,145 @@ +/** + * @file /include/ecl/command_line/xor_handler.hpp + * + * @brief TCLAP command line argument parser classes. + * + * TCLAP command line argument parser classes. + * + * @author Michael E. Smoot, Daniel J. Stonier + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef TCLAP_XORHANDLER_H +#define TCLAP_XORHANDLER_H + +#include "arg.hpp" +#include +#include +#include +#include + +namespace ecl { + +/** + * @brief TClap class indirectly used by CmdLine for handling xor'd arguments. + * + * This class handles lists of Arg's that are to be XOR'd on the command + * line. This is used by CmdLine and you shouldn't ever use it. + */ +class XorHandler +{ + protected: + + /** + * The list of of lists of Arg's to be or'd together. + */ + std::vector< std::vector > _orList; + + public: + + /** + * Constructor. Does nothing. + */ + XorHandler( ) {} + + /** + * Add a list of Arg*'s that will be orred together. + * \param ors - list of Arg* that will be xor'd. + */ + void add( std::vector& ors ); + + /** + * Checks whether the specified Arg is in one of the xor lists and + * if it does match one, returns the size of the xor list that the + * Arg matched. If the Arg matches, then it also sets the rest of + * the Arg's in the list. You shouldn't use this. + * \param a - The Arg to be checked. + */ + int check( const Arg* a ); + + /** + * Returns the XOR specific short usage. + */ + std::string shortUsage(); + + /** + * Prints the XOR specific long usage. + * \param os - Stream to print to. + */ + void printLongUsage(std::ostream& os); + + /** + * Simply checks whether the Arg is contained in one of the arg + * lists. + * \param a - The Arg to be checked. + */ + bool contains( const Arg* a ); + + std::vector< std::vector >& getXorList(); + +}; + + +////////////////////////////////////////////////////////////////////// +//BEGIN XOR.cpp +////////////////////////////////////////////////////////////////////// +inline void XorHandler::add( std::vector& ors ) +{ + _orList.push_back( ors ); +} + +inline int XorHandler::check( const Arg* a ) +{ + // iterate over each XOR list + for ( int i = 0; static_cast(i) < _orList.size(); i++ ) + { + // if the XOR list contains the arg.. + ArgVectorIterator ait = std::find( _orList[i].begin(), + _orList[i].end(), a ); + if ( ait != _orList[i].end() ) + { + // go through and set each arg that is not a + for ( ArgVectorIterator it = _orList[i].begin(); + it != _orList[i].end(); + it++ ) + if ( a != (*it) ) + (*it)->xorSet(); + + // return the number of required args that have now been set + if ( (*ait)->allowMore() ) + return 0; + else + return static_cast(_orList[i].size()); + } + } + + if ( a->isRequired() ) + return 1; + else + return 0; +} + +inline bool XorHandler::contains( const Arg* a ) +{ + for ( int i = 0; static_cast(i) < _orList.size(); i++ ) + for ( ArgVectorIterator it = _orList[i].begin(); + it != _orList[i].end(); + it++ ) + if ( a == (*it) ) + return true; + + return false; +} + +inline std::vector< std::vector >& XorHandler::getXorList() +{ + return _orList; +} + +} // namespace ecl + + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_command_line/license/AUTHORS b/ros2_ws/src/ecl_core/ecl_command_line/license/AUTHORS new file mode 100644 index 0000000..dc2a6f5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/license/AUTHORS @@ -0,0 +1,6 @@ + +original author: Michael E. Smoot +invaluable contributions: Daniel Aarno +more contributions: Erik Zeek +outstanding editing: Carol Smoot +modifications for ecl: Daniel Stonier diff --git a/ros2_ws/src/ecl_core/ecl_command_line/license/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/license/CMakeLists.txt new file mode 100644 index 0000000..e5f6443 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/license/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +set(LICENSES COPYING AUTHORS) + +install(FILES ${LICENSES} DESTINATION share/ecl/licenses/tclap) + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/license/COPYING b/ros2_ws/src/ecl_core/ecl_command_line/license/COPYING new file mode 100644 index 0000000..987be0c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/license/COPYING @@ -0,0 +1,25 @@ + + +Copyright (c) 2003 Michael E. Smoot + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/package.xml b/ros2_ws/src/ecl_core/ecl_command_line/package.xml new file mode 100644 index 0000000..83965bc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/package.xml @@ -0,0 +1,32 @@ + + + ecl_command_line + 1.2.1 + + Embeds the TCLAP library inside the ecl. This is a very convenient + command line parser in templatised c++. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_command_line + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + + ecl_license + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/src/CMakeLists.txt new file mode 100644 index 0000000..d81060b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/src/CMakeLists.txt @@ -0,0 +1,12 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(examples) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/src/examples/CMakeLists.txt new file mode 100644 index 0000000..eb83e58 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/src/examples/CMakeLists.txt @@ -0,0 +1,16 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_command_line_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_command_line_add_demo(command_line) + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/src/examples/command_line.cpp b/ros2_ws/src/ecl_core/ecl_command_line/src/examples/command_line.cpp new file mode 100644 index 0000000..713ff2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/src/examples/command_line.cpp @@ -0,0 +1,92 @@ +/** + * @file /src/examples/command_line.cpp + * + * @brief Demo program for the tclap header library. + * + * @date May, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/command_line.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::cout; +using std::cerr; +using std::endl; +using std::string; +using ecl::CmdLine; +using ecl::SwitchArg; +using ecl::ValueArg; +using ecl::UnlabeledValueArg; +using ecl::ArgException; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char** argv) { + + int test(0); + bool debug(false); + string nolabel; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Command Line Parsing" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + // Supply a program description, argument separator (optional) and version number (optional). + CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP."); +// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01"); + + // Add a boolean (flag, name, description), sets the default state to false unless it is found on the command line. + SwitchArg debugSwitch("d","debug","Enable debugging."); + // Add a boolean (flag, name, description, default) + // SwitchArg debug("d","debug","Enable debugging.", false); + cmd.add(debugSwitch); + + // Add an int (flag,name,description,compulsory flag?,default value,help description of the type") + ValueArg intArg("i","integer","An integer argument for testing.",false,5,"integer"); + cmd.add(intArg); + + // (one word argument name, long description, req/not req, default value, type) + UnlabeledValueArg nolabelArg( "echo", "An unlabeled argument", false, "dude", "string" ); + cmd.add(nolabelArg); + + /********************* + ** Parse + **********************/ + cmd.parse(argc,argv); + debug = debugSwitch.getValue(); + test = intArg.getValue(); + nolabel = nolabelArg.getValue(); + + } catch ( ArgException &e ) + { + cerr << "error: " << e.error() << " for arg " << e.argId() << endl; + } + + cout << "Test Integer: " << test << endl; + if ( debug ) { + cout << "Debug Switch (bool): true" << endl; + } else { + cout << "Debug Switch (bool): false" << endl; + } + std::cout << "Echoing unlabelled arg: " << nolabel << std::endl; + std::cout << std::endl; + + return 0; +} + + + diff --git a/ros2_ws/src/ecl_core/ecl_command_line/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_command_line/src/test/CMakeLists.txt new file mode 100644 index 0000000..056a22b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/src/test/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# Tests +############################################################################### + +# currently broken +# ament_add_gtest(test_command_line command_line.cpp) diff --git a/ros2_ws/src/ecl_core/ecl_command_line/src/test/command_line.cpp b/ros2_ws/src/ecl_core/ecl_command_line/src/test/command_line.cpp new file mode 100644 index 0000000..ed7cd9d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_command_line/src/test/command_line.cpp @@ -0,0 +1,82 @@ +/** + * @file /src/test/command_line.cpp + * + * @brief Unit Test for the tclap header library. + * + * Unit Test for the tclap header library (ecl/command_line.hpp). + * + * @date May, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/command_line.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::CmdLine; +using ecl::SwitchArg; +using ecl::ValueArg; +using ecl::ArgException; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +static int myargc; +static char **myargv; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(CommandLineTests,verify) { + try { + // Supply a program description, argument separator (optional) and version number (optional). + CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP."); +// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01"); + + // Add a boolean (flag, name, description), sets the default state to false unless it is found on the command line. + SwitchArg debugSwitch("d","debug","Enable debugging."); + // Add a boolean (flag, name, description, default) + // SwitchArg debug("d","debug","Enable debugging.", false); + cmd.add(debugSwitch); + + // Add an int (flag,name,description,compulsory flag?,default value,help description of the type") + ValueArg intArg("i","integer","An integer argument for testing.",false,5,"integer"); + cmd.add(intArg); + + /********************* + ** Parse + **********************/ + cmd.parse(myargc, myargv); // RoS gtest 'make test' breaks here. + bool debug = debugSwitch.getValue(); + int test = intArg.getValue(); + + EXPECT_EQ(5,test); + EXPECT_FALSE(debug); + + } catch ( ArgException &e ) { + ADD_FAILURE() << "Failed to parse command line arguments"; + } +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + myargc = argc; + myargv = argv; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_concepts/.cproject b/ros2_ws/src/ecl_core/ecl_concepts/.cproject new file mode 100644 index 0000000..a490453 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/.cproject @@ -0,0 +1,341 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + tests + true + true + true + + + make + + clean + true + true + true + + + make + + all + true + true + true + + + make + + test + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_concepts/.project b/ros2_ws/src/ecl_core/ecl_concepts/.project new file mode 100644 index 0000000..62b3be1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/.project @@ -0,0 +1,78 @@ + + + ecl_concepts + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_concepts/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_concepts/CHANGELOG.rst new file mode 100644 index 0000000..608f8a2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/CHANGELOG.rst @@ -0,0 +1,11 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_concepts +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +1.0.6 (2020-01-11) +------------------ +* bugfix a warning-as-error on a throw in a method declaration`#99 `_ + +0.61.13 (2016-05-03) +-------------------- +* drop unused typedefs diff --git a/ros2_ws/src/ecl_core/ecl_concepts/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/CMakeLists.txt new file mode 100644 index 0000000..ba129d7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/CMakeLists.txt @@ -0,0 +1,75 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_concepts) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Project configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + ecl_config::ecl_config + ecl_type_traits::ecl_type_traits +) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_config + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/changelog.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/changelog.dox new file mode 100644 index 0000000..d9be8e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/changelog.dox @@ -0,0 +1,19 @@ +/** + @page changelogConcepts ChangeLog + + @section Changes + + - Feb 11 : Testing class for dynamic containers. + - Oct 10 : Testing class added for ecl compatible input, output and input-output devices. + - Jul 09 : Testing class for nullary funciton objects. + - Jul 09 : Testing class for ecl and std streams. + - May 09 : Testing class for blueprint instantiation. + - May 09 : Testing class for simple containers and byte containers. + - May 09 : Macros : tools for simple concept checking finalised. + + @section Bugs + + - Feb 11 : Fixed the byte tests in the container concept to handle platform dependant typedef'ing of char. + - Jul 09 : Non-uniqueness problem when using the concept check twice in a program. Added a unique macro to fix. + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_blueprints.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_blueprints.dox new file mode 100644 index 0000000..6247ff5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_blueprints.dox @@ -0,0 +1,155 @@ +/** +@page blueprintsConcept Blueprints + +@section overviewSection Overview + +Blueprints store a minimal ruleset for instantiating or configuring +specialised representations of a class such as a uniformly filled +array, or the unit vectors of each dimension. This can of course, +be done inside a class, but via the blueprints, we introduce +an extra layer of indirection that helps get around two issues. + +@subsection whySection Problems with Constructor Overloading + +Overloading the constructor can become difficult when you cannot find a +unique signature for one of many constructor calls. For example, + +@code +A(double x, double y); +A(double r, double angle); +@endcode + +Traditionally, the way around it would be to define +a static function within the class. However, this runs into difficulty +when incorporating a 3rd party library - you cannot add static functions +to pre-existing classes. This is often very desirable if you want to create +your own pre-defined instantiations of things like matrices. So in these cases, +an externally applied method is necessary. + +@subsection whyAssignment Problems with Assignment + +Even when there are static methods available to generate specialised instances, +operator assignment will usually result in a construction followed by a +full copy, which is expensive. + +@code +Array array; +//... +array = Array::ConstantArray(3); +@endcode + +@subsection whatSection How BluePrints Work + +By generating a minimal blueprint and then passing to a class's assignment operator, +or forcing the blueprint to generate an instance externally, we resolve the two +problems above. In some cases we also get a speedup if we need to repeatedly use +a blueprint, in sofar as the blueprint can save and store the state required +to generate the class from the blueprint. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit for which you are +running compile time checks on your blueprint classes. + +@code +#include + +using ecl::BluePrintConcept; +@endcode + +Since it only uses macros and templatised objects, no linking is required for just this feature. + +@section creation Concept Definition + +Creating a blueprint class can be done in any namespace, it just has to satisfy the +three conditions outlined below: + +- base_type : a typedef for the target class for which they generate instances/configurations. +- base_type instantiate() : they must be able to instantiate a base_type object. +- void apply(base_type&) : they must be able to apply this configuration to an existing object. + +A simple example for a blueprint related to the Foo class: + +@code +class Foo { +public: + Foo(std::string &id) : name(id) {} + void changeName(std::string &new_name) { name = new_name; } + // ... +private: + std::string name; +}; + +class SimpleFoo { +public: + typdef Foo base_type; + base_type instantiate() { return Foo("simpleton"); } + void apply(base_type& foo) { + foo.changeName("simpleton"); + } +@endcode + +That, of course, was complicating a redundantly trivial situation. +A better, practicial example is the ConstantArray blueprint for array containers in ecl_containers. + +@section Usage + +@subsection check Convenient BluePrint Class Handling + +While its possible to simply use the blueprint class in the following manner (in this +example, ConstrantArray is a blueprint): + +@code +Array array = ConstantArray()(3).instantiate(); +ConstantArray()(3).apply(array); +@endcode + +It's not very convenient. I usually wrap them in a factory class which possesses static methods +that will either result in instantiations or blueprints. A direct implementation of such a factory might like like this: + +@code +Array array = ArrayFactory::ConstantArray(3); // Construction +ArrayFactory::ConstantArray(array,3); // Assignment +@endcode + +This is about as far as you can go with a factory class working for a 3rd party class that you +cannot modify. If however, you can modify the base_type class, then it is possible to +insert a constructor and assignment operator to directly handle blueprints, e.g. in the +Array container class (ecl_containers), we have the following declarations: + +@code + template + Array(const T& blueprint) { + compile_time_concept_check(BluePrintConcept); + blueprint.apply(*this); + } + + template + void operator=(const T& blueprint) { + compile_time_concept_check(BluePrintConcept); + blueprint.apply(*this); + } +@endcode +Then we can handle both construction and assignment equivalently: +@code +Array array = ArrayFactory::ConstantArray(3); // Construction +array = ArrayFactory::ConstantArray(3); // Assignment (no costly copy) +@endcode + +Furthermore, if our base class inherits the factory, then we can simplify this further: +@code +Array array = Array::ConstantArray(3); // Construction +array = Array::ConstantArray(3); // Assignment (no costly copy) +@endcode + +@section Examples + +These are the relevant components for array type blueprints which can be found in ecl_containers. + +- ecl::Array +- ecl::blueprints::ArrayFactory +- ecl::blueprints::ConstantArray + +@section Changelog +- Blueprint testing class added [May 09]. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_containers.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_containers.dox new file mode 100644 index 0000000..5a2e9b6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_containers.dox @@ -0,0 +1,67 @@ +/** +@page containersConcept Containers + +@section overviewSection Overview + +Containers have a few properties in common that can simplify the +passing of or the development of methods that use generic containers. Rather +than having a suite of overloaded functions, a simple template argument with +a concept check will suffice for all variants. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit for which you are +running compile time checks on your blueprint classes. + +@code +#include + +using ecl::ContainerConcept; +using ecl::DynamicContainerConcept; +using ecl::UnsignedByteContainerConcept; +using ecl::SignedByteContainerConcept; +@endcode + +Since it only uses macros and templatised objects, no linking is required for just this feature. + +@section creation Container Concept Definition + +Classes passing the ContainerConcept must satisfy: + +- begin() : a method for retrieving a pointer/iterator to the start of the container. +- end() : a method for retrieving a pointer/iterator to the end of the container. +- size() : a method for retrieving the number of elements stored in the container. + +@subsection dynamic Dynamic Containers + +Classes passing the DynamicContainerConcept must additionally satisfy: + +- resize(int) : a method for resizing the number of elements managed by the container. + +@subsection byte Byte Containers + +In addition, if it is testing for a byte container, then it will do a check on the value type +in the container and fail if it is not a char (uses a trick via specialisations and private +constructors to ensure a compile time failure). + +@section Usage + +Use with the compile time concept check whenever you wish to check for a container template class. + +@code + template + void f(const T& container) { + compile_time_concept_check(ContainerConcept); + unsigned int size = container.size(); + //... + } + template + void g(const T& byte_container) { + compile_time_concept_check(SignedByteContainerConcept); + unsigned int size = container.size(); + char c = container[0]; + //... + } +@endcode + + **/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_devices.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_devices.dox new file mode 100644 index 0000000..533dc95 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_devices.dox @@ -0,0 +1,77 @@ +/** +@page devicesConcept Devices + +@section overviewSection Overview + +Rather than provide a complex inheritable family of classes with super-imposed mixins +to represent the varying degrees of generic device functionalities +(e.g. source, sink, seekable...) a rather more simpler (and faster) concept +based method is used for the devices in ecl's input-output library. The concepts +are required to validate the classes for use by higher level structures such as streams. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit for which you are +running compile time checks on your blueprint classes. + +@code +#include + +using ecl::InputCharDeviceConcept; +using ecl::OutputCharDeviceConcept; +using ecl::InputOutputCharDeviceConcept; +using ecl::InputByteDeviceConcept; +using ecl::OutputByteDeviceConcept; +using ecl::InputOutputByteDeviceConcept; +@endcode + +Since it only uses macros and templatised objects, no linking is required for just this feature. + +@section creation Concept Definitions + +@subsection InputCharDevice + +An input device class has to satisfy the following conditions: + +- long read(char &c) : read a single character from the device buffer. +- long read(char *s, unsigned long n) : read a char buffer from the device buffer. + +@subsection OutputCharDevice + +An output device class has to satisfy the following conditions: + +- long write(char &c) : write a single character from the device buffer. +- long write(char *s, unsigned long n) : write a char buffer from the device buffer. +- void flush() : a method for flushing the output device buffer to the device. + +@subsection InputOutputCharDevice + +An input-output device class has to satisfy the conditions required by both input and output devices +simultaneously. + +@subsection ByteDevice + +The three byte device concepts are similar except they add additional read/write capabilities for the other +is_byte types (refer to ecl_mpl's type traits). Namely char, signed char and unsigned char. + +@section Usage + +Generally, you won't need to use these directly. Rather they're embedded in other ecl objects +such as streams. However, a simple example of a device function definition and the concept check usage is outlined below. + +@code +#include + +using ecl::InputCharDevice; + +template +class MyStream { +public: + + MyStream(Device *device) { + compile_time_concept_check(InputCharDeviceConcept); + } +}; +@endcode + + **/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_nullary_functions.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_nullary_functions.dox new file mode 100644 index 0000000..2f2591a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_nullary_functions.dox @@ -0,0 +1,42 @@ +/** +@page nullaryFunctionConcept Nullary Functions + +@section overviewSection Overview + +Nullary functions are defined as an object (c++ class/struct) that is +sometimes otherwise known as callable without any argument passing. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit for which you are +running compile time checks on your blueprint classes. + +@code +#include + +using ecl::NullaryFunctionConcept; +@endcode + +Since it only uses macros and templatised objects, no linking is required for just this feature. + +@section creation Concept Definition + +Creating a class can be done in any namespace, it just has to satisfy the +conditions outlined below: + +- operator()() : a method for executing the nullary function object. +- typedef result_type : a typedef to the return type of the operator. + +@section Usage + +Use with the compile time concept check whenever you wish to check for a nullary function object input. +For example, the Thread class (ecl_threads) utilises this in a similar way to that outlined +below: + +@code + template + Thread(F function) { + compile_time_concept_check(NullaryFunctionConcept); + } +@endcode +**/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_streams.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_streams.dox new file mode 100644 index 0000000..0cc93dd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/concept_streams.dox @@ -0,0 +1,65 @@ +/** +@page streamsConcept Streams + +@section overviewSection Overview + +Many of the ecl classes are streamable, in order to provide quick visual +debugging of its contents. Typically in c++ the default streaming object +is the ostream object, however the io module here extends streaming +functionalities to almost every device. The important caveat though, is +they do not use the c++ iostream overheads (these are very costly). + +In order to accomodate both (and also perhaps third party streams), the +streams concept has been defined so streaming with a generalised template +function is convenient. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit for which you are +running compile time checks on your blueprint classes. + +@code +#include + +using ecl::StreamsConcept; +@endcode + +Since it only uses macros and templatised objects, no linking is required for just this feature. + +@section creation Concept Definition + +A streaming class just has to satisfy the following conditions: + +- operator << : can stream characters. +- flush() : a method which writes the stream to an underlying device or object. + +Note that the object instance cout automatically satisfies these. + +@section Usage + +A simple example of a streaming function definition and the concept check usage is outlined below. + +@code +#include + +using ecl::Stream; + +class MyMatrix { +public: + template + friend OutputStream& operator << (OutputStream &ostream, MyMatrix &matrix); +}; + +template +OutputStream& operator << (OutputStream &ostream, MyMatrix &matrix) { + + compile_time_concept_check(StreamConcept); + + ostream << "Hello Dudes, this is a matrix\n"; + + ostream.flush(); + return ostream; +} +@endcode + + **/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/mainpage.dox new file mode 100644 index 0000000..6ab5ac7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/mainpage.dox @@ -0,0 +1,116 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + +One of the problem with template usage occurs occurs in the following scenario. +For templatised functions and classes, the input template arguments +usually have little or no restriction on the class that can be used, e.g. +@code +template +void f(T input) { + // use some aspect of T's interface +} +@endcode + +Of course the compile will fail if you try to use an input type, T, that doesn't have the +specialised interface you want, but the compile time error message is often very verbose +and its difficult to find the error. An idea which is merging into the c++ mainstream as +well as that used by the boost concept checking library is to characterise common +behaviours into Concepts. A simplified version of this is utilised here. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit that requires +compilation of signals and/or slots. + +@code +#include + +// The concept definition/validation classes. +using ecl::BluePrintConcept; +using ecl::ContainerConcept; +using ecl::SignedByteContainerConcept; +using ecl::UnsignedByteContainerConcept; +using ecl::NullaryFunctionConcept; +using ecl::StreamConcept; +using ecl::InputCharDeviceConcept; +using ecl::OutputCharDeviceConcept; +using ecl::InputOutputCharDeviceConcept; +using ecl::InputByteDeviceConcept; +using ecl::OutputByteDeviceConcept; +using ecl::InputOutputByteDeviceConcept; + +@endcode + +Since it is a collection of macros and template functions/classes, no linking +is required if you are only utilising this functionality. + +@section Usage + +Usage is fairly simple. There are two steps: + +- Concept Test : must be hand crafted to check all the characteristic behaviours of a concept. +- Concept Check : whenever required, call the concept check which runs the concept test to verify compliance. + +@subsection conceptTestSection Concept Test + +If you are using an existing concept (see below), skip through to the concept check. Otherwise: + +- Decide on a name for the concept. +- Create a templatised class of that name with a single arbitrary template argument (the class to be tested). +- Hand craft the testing function within that class using compile_time_concept_test(). + +The example here is the same as that used in src/tests/concepts.cpp: + +@code +template +class MyConcept { + public: + compile_time_concept_test(MyConcept) { + T t; + t.apply(); // This is the characteristic function required by this concept. + } +}; +@endcode +Hand-crafting the concept testing function will often require a little care to ensure the concept +is appropriately covered. + +@subsection conceptCheckSection Concept Check + +Once you have a test in place, you only need to insert compile_time_concept_check() calls wherever you need them. +Keep in mind, the sole purpose of these is to provide convenient error logs when something +goes wrong. +@code +class A { // This class has the MyConcept functionality. + public: + // The following function characterises the MyConcept concept. + // Comment this line and any MyConcept concept assertion + // check will fail in compile time. + void apply() {}; +}; + +int main() { + compile_time_concept_check(MyConcept); // Checks A for compliance to the MyConcept concept. + return 0; +} +@endcode + +@section conceptsList Existing Concepts + +- @ref blueprintsConcept "BluePrints" - checks for blueprint functionality as defined in ecl_utilities. +- @ref containersConcept "Containers" - also bytecontainer, simple checks for basic prerequisite container methods. +- @ref nullaryFunctionConcept "NullaryFunctions" - function objects which require no arguments in execution. +- @ref streamsConcept "Streams" - any class with basic char streaming capabilities. +- @ref devicesConcept "Devices" - device functionalities compatible to those in ecl_devices. + +@section Examples + +- src/test/concepts.cpp + +@section ChangeLog + + - @ref changelogConcepts "ChangeLog" + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/namespaces.dox new file mode 100644 index 0000000..55ac604 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/doxygen/namespaces.dox @@ -0,0 +1,22 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::concepts + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ +/** + * @namespace ecl::concepts::tests + * + * @brief Frameworks created for the unit tests. + * + * Includes everything that was also added for compiling the unit tests. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..678d03d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(concepts) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts.hpp new file mode 100644 index 0000000..ed9fee7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts.hpp @@ -0,0 +1,28 @@ +/** + * @file /include/ecl/concepts.hpp + * + * @brief Compile time meta-programming concepts. + * + * Compile time meta-programming concepts. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_HPP_ +#define ECL_CONCEPTS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "concepts/macros.hpp" +#include "concepts/blueprints.hpp" +#include "concepts/containers.hpp" +#include "concepts/devices.hpp" +#include "concepts/nullary_function.hpp" +#include "concepts/streams.hpp" + +#endif /* ECL_CONCEPTS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/CMakeLists.txt new file mode 100644 index 0000000..5002422 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/concepts) diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/blueprints.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/blueprints.hpp new file mode 100644 index 0000000..cceaa24 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/blueprints.hpp @@ -0,0 +1,58 @@ +/** + * @file /include/ecl/concepts/blueprints.hpp + * + * @brief Lightweight objects used for custom class instantiation and assignment. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_BLUEPRINTS_HPP_ +#define ECL_CONCEPTS_BLUEPRINTS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Concept [BluePrint] +*****************************************************************************/ + +/** + * @brief Defines validating functionality for the @ref blueprintsConcept "blueprint concept". + **/ +template +class BluePrintConcept { +public: + /** + * @brief Implements a concept test for blueprints. + * + * There are three conditions required by blueprints: + * - base_type : a typedef for the target class for which they generate instances/configurations. + * - base_type instantiate() : they must be able to instantiate a base_type object. + * - void apply(base_type&) : they must be able to apply this configuration to an existing object. + */ + ecl_compile_time_concept_test(BluePrintConcept) + { + target = blue_print.instantiate(); + blue_print.apply(target); + } + +private: + typename Implementation::base_type target; + Implementation blue_print; +}; + +} // namespace ecl + +#endif /* ECL_CONCEPTS_BLUEPRINTS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/containers.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/containers.hpp new file mode 100644 index 0000000..deefc0a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/containers.hpp @@ -0,0 +1,342 @@ +/** + * @file /include/ecl/concepts/containers.hpp + * + * @brief Defines and validates the functionality for the container concept. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_ +#define ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Concept [Container] +*****************************************************************************/ + +/** + * @brief Defines validating functionality for the @ref containersConcept "container concept". + **/ +template +class ContainerConcept { +public: + + /** + * @brief Implements a concept test for containers. + * + * The following conditions are required by containers: + * + * - begin() : a method for retrieving a pointer/iterator to the start of the container. + * - end() : a method for retrieving a pointer/iterator to the end of the container. + * - size() : a method for retrieving the number of elements stored in the container. + * - value_type : a typedef for the element type stored in the container. + */ + ecl_compile_time_concept_test(ContainerConcept) + { + iter = container.begin(); + iter = container.end(); + unsigned int n; + n = container.size(); + (void) n; // remove set but not used warnings. + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation container; + typename Implementation::iterator iter; +}; +/** + * @brief Defines validating functionality for the dynamic @ref containersConcept "container concept". + **/ +template +class DynamicContainerConcept { +public: + + /** + * @brief Implements a concept test for containers. + * + * The following conditions are required by containers: + * + * - begin() : a method for retrieving a pointer/iterator to the start of the container. + * - end() : a method for retrieving a pointer/iterator to the end of the container. + * - size() : a method for retrieving the number of elements stored in the container. + * - resize(int) : a method for resizing the container. + * - value_type : a typedef for the element type stored in the container. + */ + ecl_compile_time_concept_test(DynamicContainerConcept) + { + iter = container.begin(); + iter = container.end(); + unsigned int n; + n = container.size(); + container.resize(1); + (void) n; // remove set but not used warnings. + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation container; + typename Implementation::iterator iter; +}; + +/** + * @cond DO_NOT_DOXYGEN + */ +namespace concepts { + +/** + * @brief Back end to the signed byte test check. + * + * Used to invalidate with a private constructor when the condition is right. + * This is the one that will show up in the printout for a compile time + * error. + * + * Do not use this one directly, use SignedByteTestCheck to make use of it. + */ +template +class SignedByteTest { +private: + SignedByteTest() {} +}; + +/** + * @brief Back end to the signed byte test check. + * + * Used to toggle a valid public constructor when the condition is right. + * This is the one that will show up in the printout for a compile time + * error. + * + * Do not use this one directly, use SignedByteTestCheck to make use of it. + */ +template +class SignedByteTest { +public: + SignedByteTest() {} +}; + +/** + * @brief Back end to the unsigned byte test check. + * + * Used to invalidate with a private constructor when the condition is right. + * This is the one that will show up in the printout for a compile time + * error. + * + * Do not use this one directly, use UnsignedByteTestCheck to make use of it. + */ +template +class UnsignedByteTest { +private: + UnsignedByteTest() {} +}; + +/** + * @brief Back end to the unsigned byte test check. + * + * Used to toggle a valid public constructor when the condition is right. + * This is the one that will show up in the printout for a compile time + * error. + * + * Do not use this one directly, use UnsignedByteTestCheck to make use of it. + */ +template +class UnsignedByteTest { +public: + UnsignedByteTest() {} +}; + +/** + * @brief Front end to the signed byte test check. + * + * Forces it to throw a compile time error if the check fails because + * the parent implementation will have a private constructor. + */ +template +class SignedByteTestCheck : public SignedByteTest::value > {}; + +/** + * @brief Front end to the unsigned byte test check. + * + * Forces it to throw a compile time error if the check fails because + * the parent implementation will have a private constructor. + */ +template +class UnsignedByteTestCheck : public UnsignedByteTest::value > {}; + +/** + * @brief Used to invalidate non char types storage. + * + * This is the default template class for the unsigned character test - if the + * specialisation from the byte container element type being tested is + * not a char type, it will use this and result in a compile time error + * since the constructor is private! + */ +template +class ByteTest { +private: + ByteTest() {} +}; + +/** + * @brief Used to validate char types storage. + * + * Containers with a unsigned char storage element will use this specialisation + * when doing the byte container concept check. This results in no + * compile time error as the constructor is public (as opposed to + * the generalised instance which has a private constructor). + */ +template <> +class ByteTest { +public: + ByteTest() {} +}; +/** + * @brief Used to validate char types storage as byte storage. + */ +template <> +class ByteTest { +public: + ByteTest() {} +}; + +/** + * @brief Used to validate signed char types storage as byte storage. + */ +template <> +class ByteTest { +public: + ByteTest() {} +}; + +} // namespace concepts +/** + * @endcond + */ + +/** + * @brief Defines validating functionality for the byte container concept. + **/ +template +class UnsignedByteContainerConcept { +public: + + /** + * @brief Implements a concept test for byte containers. + * + * The following conditions are required by byte containers: + * - begin() : a method for retrieving a pointer/iterator to the start of the container. + * - end() : a method for retrieving a pointer/iterator to the end of the container. + * - size() : a method for retrieving the number of elements stored in the container. + * - value_type : a typedef for the element type stored in the container, must be unsigned char. + */ + ecl_compile_time_concept_test(UnsignedByteContainerConcept) + { + typedef typename Implementation::value_type element_type; + iter = container.begin(); + iter = container.end(); + unsigned int n; + n = container.size(); + // If not a char, this results in a private call -> compile time error! + concepts::UnsignedByteTestCheck char_test; + (void) n; // remove set but unused warnings. + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation container; + typename Implementation::iterator iter; +}; + +/** + * @brief Defines validating functionality for the signed byte container concept. + **/ +template +class SignedByteContainerConcept { +public: + + /** + * @brief Implements a concept test for byte containers. + * + * The following conditions are required by byte containers: + * - begin() : a method for retrieving a pointer/iterator to the start of the container. + * - end() : a method for retrieving a pointer/iterator to the end of the container. + * - size() : a method for retrieving the number of elements stored in the container. + * - value_type : a typedef for the element type stored in the container, must be signed char. + */ + ecl_compile_time_concept_test(SignedByteContainerConcept) + { + typedef typename Implementation::value_type element_type; + iter = container.begin(); + iter = container.end(); + unsigned int n; + n = container.size(); + // If not a char, this results in a private call -> compile time error! + concepts::SignedByteTestCheck char_test; + (void) n; + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation container; + typename Implementation::iterator iter; +}; + +/** + * @brief Defines validating functionality for the byte container concept. + * + * Elements stored in this container can be either signed, unsigned or char type. + **/ +template +class ByteContainerConcept { +public: + + /** + * @brief Implements a concept test for byte containers. + * + * The following conditions are required by byte containers: + * - begin() : a method for retrieving a pointer/iterator to the start of the container. + * - end() : a method for retrieving a pointer/iterator to the end of the container. + * - size() : a method for retrieving the number of elements stored in the container. + * - value_type : a typedef for the element type stored in the container, must be char, signed char or unsigned char. + */ + ecl_compile_time_concept_test(ByteContainerConcept) + { + typedef typename Implementation::value_type element_type; + iter = container.begin(); + iter = container.end(); + unsigned int n; + n = container.size(); + // If not a char, this results in a private call -> compile time error! + concepts::ByteTest char_test; + (void) n; // remove set but unused warnings. + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation container; + typename Implementation::iterator iter; +}; + +} // namespace ecl + +#endif /* ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/devices.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/devices.hpp new file mode 100644 index 0000000..722060e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/devices.hpp @@ -0,0 +1,320 @@ +/** + * @file /include/ecl/concepts/devices.hpp + * + * @brief Defines validating functionality for the device concepts. + * + * Defines validating functionality for the device concepts. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_DEVICES_HPP_ +#define ECL_CONCEPTS_DEVICES_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Concept [InputCharDevice] +*****************************************************************************/ + +/** + * @brief Validates functionality for the @ref devicesConcept "input char device concept". + * + * This checks if a device can handle input of char types. + **/ +template +class InputCharDeviceConcept { +public: + /** + * @brief Implements a concept test for input devices. + * + * The following conditions are required by input devices: + * + * - long read(char &c) : read a single character from the device buffer. + * - long read(char *s, unsigned long n) : read a char buffer from the device buffer. + */ + ecl_compile_time_concept_test(InputCharDeviceConcept) { + char c; + char buffer[10]; + long no_read; + bool result; + result = input_char_device.open(); + no_read = input_char_device.read(c); + no_read = input_char_device.read(buffer,10); + (void) no_read; // remove set but unused warnings + (void) result; // remove set but unused warnings + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation input_char_device; +}; + +/***************************************************************************** +** Concept [OutputCharDevice] +*****************************************************************************/ +/** + * @brief Validates functionality for the @ref devicesConcept "output char device concept". + * + * This checks if a device can handle output of char types. + **/ +template +class OutputCharDeviceConcept { +public: + /** + * @brief Implements a concept test for output char devices. + * + * The following conditions are required by output char devices: + * + * - long write(char &c) : write a single character to the device buffer. + * - long write(char *s, unsigned long n) : write a char buffer to the device buffer. + * - void flush() : a method for flushing the output device buffer to the device. + */ + ecl_compile_time_concept_test(OutputCharDeviceConcept) + { + long no_written; + char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + bool result; + result = output_char_device.open(); + no_written = output_char_device.write('\n'); + no_written = output_char_device.write(write_buffer,5); + output_char_device.flush(); + (void) no_written; // remove set but unused warnings + (void) result; // remove set but unused warnings + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation output_char_device; +}; + +/***************************************************************************** +** Concept [InputOutputByteDevice] +*****************************************************************************/ + +/** + * @brief Validates functionality for the @ref devicesConcept "input-output char device concept". + * + * This checks if a device can handle input-output of char types. + **/ +template +class InputOutputCharDeviceConcept { +public: + /** + * @brief Implements a concept test for input-output byte devices. + * + * The following conditions are required by input-output byte devices: + * + * - long read(char &c) : read a single character from the device buffer. + * - long read(char *s, unsigned long n) : read a char buffer from the device buffer. + * - long write(char &c) : write a single character to the device buffer. + * - long write(char *s, unsigned long n) : write a char buffer to the device buffer. + * - void flush() : a method for flushing the output device buffer to the device. + */ + ecl_compile_time_concept_test(InputOutputCharDeviceConcept) + { + char c; + char read_buffer[10]; + long no_read; + no_read = input_output_char_device.read(c); + no_read = input_output_char_device.read(read_buffer,10); + long no_written; + char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + no_written = input_output_char_device.write('\n'); + no_written = input_output_char_device.write(write_buffer,5); + input_output_char_device.flush(); + (void) no_written; + (void) no_read; + } +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation input_output_char_device; +}; + +/***************************************************************************** +** Concept [InputByteDevice] +*****************************************************************************/ + +/** + * @brief Validates functionality for the @ref devicesConcept "input byte device concept". + * + * This checks if a device can handle input of all char types + * (char, signed char, unsigned char). + **/ +template +class InputByteDeviceConcept { +public: + /** + * @brief Implements a concept test for input devices. + * + * The following conditions are required by input devices: + * + * - long read(char &c) : read a single character from the device buffer. + * - long read(char *s, unsigned long n) : read a char buffer from the device buffer. + * + * Along with the same function implemented for signed and unsigned char types. + */ + ecl_compile_time_concept_test(InputByteDeviceConcept) { + signed char sc; + signed char sbuffer[10]; + char c; + char buffer[10]; + unsigned char usc; + unsigned char usbuffer[10]; + long no_read; + bool result; + result = input_byte_device.isOpen(); + no_read = input_byte_device.read(sc); + no_read = input_byte_device.read(sbuffer,10); + no_read = input_byte_device.read(c); + no_read = input_byte_device.read(buffer,10); + no_read = input_byte_device.read(usc); + no_read = input_byte_device.read(usbuffer,10); + (void) result; + (void) no_read; + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation input_byte_device; +}; + +/***************************************************************************** +** Concept [OutputByteDevice] +*****************************************************************************/ +/** + * @brief Validates functionality for the @ref devicesConcept "output byte device concept". + * + * This checks if a device can handle output of all char types + * (char, signed char, unsigned char). + **/ +template +class OutputByteDeviceConcept { +public: + /** + * @brief Implements a concept test for output byte devices. + * + * The following conditions are required by output byte devices: + * + * - long write(char &c) : write a single character to the device buffer. + * - long write(char *s, unsigned long n) : write a char buffer to the device buffer. + * - void flush() : a method for flushing the output device buffer to the device. + * + * Along with the write function implemented for signed and unsigned char types. + */ + ecl_compile_time_concept_test(OutputByteDeviceConcept) + { + long no_written; + signed char sc = '\n'; + char c = '\n'; + unsigned char usc = 0x01; + signed char s_write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + unsigned char us_write_buffer[] = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + bool result; + result = output_byte_device.isOpen(); + no_written = output_byte_device.write(sc); + no_written = output_byte_device.write(c); + no_written = output_byte_device.write(usc); + no_written = output_byte_device.write(s_write_buffer,5); + no_written = output_byte_device.write(write_buffer,5); + no_written = output_byte_device.write(us_write_buffer,5); + output_byte_device.flush(); + (void) no_written; + (void) result; + } + +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation output_byte_device; +}; + +/***************************************************************************** +** Concept [InputOutputByteDevice] +*****************************************************************************/ + +/** + * @brief Validates functionality for the @ref devicesConcept "input-output byte device concept". + * + * This checks if a device can handle input-output of all char types + * (char, signed char, unsigned char). + **/ +template +class InputOutputByteDeviceConcept { +public: + /** + * @brief Implements a concept test for input-output byte devices. + * + * The following conditions are required by input-output byte devices: + * + * - long read(char &c) : read a single character from the device buffer. + * - long read(char *s, unsigned long n) : read a char buffer from the device buffer. + * - long write(char &c) : write a single character to the device buffer. + * - long write(char *s, unsigned long n) : write a char buffer to the device buffer. + * - void flush() : a method for flushing the output device buffer to the device. + * + * Along with the read/write functions implemented for signed and unsigned char types. + */ + ecl_compile_time_concept_test(InputOutputByteDeviceConcept) + { + signed char sc; + signed char sbuffer[10]; + char c; + char buffer[10]; + unsigned char usc; + unsigned char usbuffer[10]; + long no_read; + bool result; + result = input_output_byte_device.isOpen(); + no_read = input_output_byte_device.read(sc); + no_read = input_output_byte_device.read(sbuffer,10); + no_read = input_output_byte_device.read(c); + no_read = input_output_byte_device.read(buffer,10); + no_read = input_output_byte_device.read(usc); + no_read = input_output_byte_device.read(usbuffer,10); + + long no_written; + sc = '\n'; + c = '\n'; + usc = 0x01; + signed char s_write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' }; + unsigned char us_write_buffer[] = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + no_written = input_output_byte_device.write(sc); + no_written = input_output_byte_device.write(c); + no_written = input_output_byte_device.write(usc); + no_written = input_output_byte_device.write(s_write_buffer,5); + no_written = input_output_byte_device.write(write_buffer,5); + no_written = input_output_byte_device.write(us_write_buffer,5); + input_output_byte_device.flush(); + (void) no_read; + (void) no_written; + (void) result; + } +private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation input_output_byte_device; +}; + +} // namespace ecl + +#endif /* ECL_CONCEPTS_DEVICES_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/macros.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/macros.hpp new file mode 100644 index 0000000..87941e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/macros.hpp @@ -0,0 +1,126 @@ +/** + * @file /include/ecl/concepts/macros.hpp + * + * @brief Mechanisms enabling compile time checking of metaprogramming concepts. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_MACROS_HPP_ +#define ECL_CONCEPTS_MACROS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace concepts { + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @cond DO_NOT_DOXYGEN + */ + + /** + * @brief Initiates the concept checking function test. + * + * The function test resides in the void function pointer argument. When + * this class gets instantiated, the code in the void function pointer will + * compile. + */ + template struct InstantiateConceptCheck {}; + + /** + * This function runs the concept check, and if it fails, the compile time + * error will be reported as having come from here by including the name + * of this function (hence the use of caps and the appropriate naming of the + * function) in the error output message. + */ + template + void CONCEPT_CHECK_FAILED() + { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wnonnull" + ((Model*)0)->~Model(); + #pragma GCC diagnostic pop + } + + /** + * @brief Instantiates the compile time concept error checking process. + * + * Instantiates the compile time error checking process. If it ultimately + * fails, then there will be an error message emitted by this class (hence + * the use of caps and the appropriate naming of the class). + */ + template + struct CONCEPT_CHECK + { + InstantiateConceptCheck< CONCEPT_CHECK_FAILED > x; /**< @brief Instantiates the compile time concept checking code. **/ + enum { instantiate = 1 /**< @brief Simple flag to report success of the concept check. **/ }; + }; + /** + * @endcond + */ +} // namespace concepts +} // namespace ecl + +#define ecl_concept_check_name_expand(Name) ConceptCheck ## Name +#define ecl_concept_check_name(Name) ecl_concept_check_name_expand(Name) + +/** + * @addtogroup Macros + * @{ +**/ +/** + * @def ecl_compile_time_concept_check + * + * @brief Compile time concept checking assertion. + * + * This macro checks a class to verify if it conforms to a compile time metaprogramming + * concept. + * + * Usage: + * + * The input argument to this macro function is the concept class type with + * the testing class as its template parameter. + * @code + * ecl_compile_time_concept_check(MyConcept); + * @endcode + */ +#define ecl_compile_time_concept_check( Model ) \ + enum { ecl_concept_check_name(__LINE__) = ecl::concepts::CONCEPT_CHECK< Model >::instantiate } + +/** + * @def ecl_compile_time_concept_test + * + * @brief Convenient notational macro for setting up a concept testing function. + * + * The actual mechanics of concept testing has to be implemented in the concept class' destructor. + * This macro is purely just a notational convenience that makes it clear when programming + * the precise meaning of what is intended for your concept class. + * + * Usage: + * + * @code + * class MyConcept { + * public: + * ecl_compile_time_concept_test(MyConcept) + * { + * // compile time concept checks here. + * } + * }; + * @endcode + */ +#define ecl_compile_time_concept_test( Model ) \ + ecl_compile_time_concept_check( Model ); \ + ~Model() + +/** + * @} + **/ +#endif /* ECL_CONCEPTS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/nullary_function.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/nullary_function.hpp new file mode 100644 index 0000000..bb5a7f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/nullary_function.hpp @@ -0,0 +1,65 @@ +/** + * @file /include/ecl/concepts/nullary_function.hpp + * + * @brief Defines validating the functionality for the nullary function concept. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_NULLARY_FUNCTION_HPP_ +#define ECL_CONCEPTS_NULLARY_FUNCTION_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Concept [Container] +*****************************************************************************/ + +/** + * @brief Defines validating functionality for the @ref nullaryFunctionConcept "nullary function concept". + **/ +template +class NullaryFunctionConcept { + public: + + /** + * @brief Implements a concept test for nullary functions. + * + * The following conditions are required by nullary functions: + * + * - operator()() : a method which calls the nullary function. + * - result_type : a typedef for the return type of the nullary function. + */ + ecl_compile_time_concept_test(NullaryFunctionConcept) + { + typedef typename Implementation::result_type ECL_UNUSED return_type; + function(); + // Unfortunately we can't test for the result type to match a certain value here + // as this would then have 2 template arguments with a separating comma. That throws + // the compile_time_concept_check macro into thinking it has two macro arguments. + } + + private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation function; +}; + +} // namespace ecl + +#endif /* ECL_CONCEPTS_NULLARY_FUNCTION_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/streams.hpp b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/streams.hpp new file mode 100644 index 0000000..24a20b0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/include/ecl/concepts/streams.hpp @@ -0,0 +1,63 @@ +/** + * @file /include/ecl/concepts/streams.hpp + * + * @brief Defines and validates functionality for the streams concept. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONCEPTS_STREAMS_HPP_ +#define ECL_CONCEPTS_STREAMS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Concept [Stream] +*****************************************************************************/ + +/** + * @brief Defines validating functionality for the @ref streamsConcept "streams concept". + * + * This only requires very minimal level functionality for streams, most std + * io streams as well as the ecl streams will work with it. + **/ +template +class StreamConcept { + public: + + /** + * @brief Implements a concept test for streams. + * + * The following conditions are required by streams: + * + * - operator<< : a streaming operator which works on at least, chars. + * - flush() : a method for flushing the stream to the underlying device. + */ + ecl_compile_time_concept_test(StreamConcept) + { + stream << 'a'; + stream.flush(); + } + + private: + // Putting instantiations here actually saves instantiation (which can cause a + // problem if there is no default constructor). + Implementation stream; +}; + +} // namespace ecl + +#endif /* ECL_CONCEPTS_STREAMS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_concepts/package.xml b/ros2_ws/src/ecl_core/ecl_concepts/package.xml new file mode 100644 index 0000000..61da64b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/package.xml @@ -0,0 +1,37 @@ + + + ecl_concepts + 1.2.1 + + Introduces a compile time concept checking mechanism that can be used + most commonly to check for required functionality when passing + template arguments. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_concepts + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_type_traits + + ecl_license + ecl_config + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_concepts/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/src/CMakeLists.txt new file mode 100644 index 0000000..8750f10 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/src/CMakeLists.txt @@ -0,0 +1,9 @@ +############################################################################### +# Subdirectories +############################################################################### + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_concepts/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_concepts/src/test/CMakeLists.txt new file mode 100644 index 0000000..784675b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/src/test/CMakeLists.txt @@ -0,0 +1,17 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_concepts_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Tests +############################################################################### + +ecl_concepts_add_gtest(concepts) \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_concepts/src/test/concepts.cpp b/ros2_ws/src/ecl_core/ecl_concepts/src/test/concepts.cpp new file mode 100644 index 0000000..0ad6f5a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_concepts/src/test/concepts.cpp @@ -0,0 +1,102 @@ +/** + * @file /src/test/concepts.cpp + * + * @brief Unit Test for concept checking. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/concepts/blueprints.hpp" +#include "../../include/ecl/concepts/containers.hpp" +#include "../../include/ecl/concepts/macros.hpp" +#include "../../include/ecl/concepts/streams.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Classes +*****************************************************************************/ + +namespace ecl { +namespace concepts { +namespace tests { + +template +class Concept { + public: + ecl_compile_time_concept_test(Concept) + { + T t; + t.apply(); // This is the characteristic function required by this concept. + } +}; + +class A { + public: + void apply() {}; // Comment this line to cause the compile to fail. +}; + +class BluePrintCandidate { +public: + typedef int base_type; + base_type instantiate(); + void apply(base_type dude); +}; + +} // namespace tests +} // namespace concepts +} // namespace ecl + +/***************************************************************************** +** Tests +*****************************************************************************/ + +using namespace ecl::concepts::tests; + +// By default, the concept tests will pass. To cause it to fail +// comment the concept test functions and rebuild. + + +TEST(CompileTimeTests,macro) { + ecl_compile_time_concept_check(Concept); + EXPECT_TRUE(true); // Should only fall over if compile time check is triggered. +} + +TEST(CompileTimeTests,stream) { + ecl_compile_time_concept_check(ecl::StreamConcept); + EXPECT_TRUE(true); // Should only fall over if compile time check is triggered. +} + +TEST(CompileTimeTests,blueprint) { + ecl_compile_time_concept_check(ecl::BluePrintConcept); + EXPECT_TRUE(true); // Should only fall over if compile time check is triggered. +} + +TEST(CompileTimeTests,container) { + ecl_compile_time_concept_check(ecl::DynamicContainerConcept< std::vector >); + EXPECT_TRUE(true); // Should only fall over if compile time check is triggered. +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +/** + * @endcond + */ + diff --git a/ros2_ws/src/ecl_core/ecl_containers/.cproject b/ros2_ws/src/ecl_core/ecl_containers/.cproject new file mode 100644 index 0000000..bb1b132 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/.cproject @@ -0,0 +1,338 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + -f ../../${ProjName}/Makefile -j8 + all + true + true + true + + + make + -j8 + clean + true + true + true + + + make + -j8 + test + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_containers/.project b/ros2_ws/src/ecl_core/ecl_containers/.project new file mode 100644 index 0000000..0e628f0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/.project @@ -0,0 +1,82 @@ + + + ecl_containers + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + pwd + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:ecl_containers} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + -L + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + false + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_containers/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_containers/CHANGELOG.rst new file mode 100644 index 0000000..8b5a5b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/CHANGELOG.rst @@ -0,0 +1,16 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +0.61.18 (2017-06-26) +-------------------- +* bugfix trivial gcc7.1 error + +0.61.2 (2015-08-12) +------------------- +* byte array converters for long long + +0.61.0 (2014-09-12) +------------------- +* stencil for unsigned char* arrays. +* byte array converters for vector based stencils. diff --git a/ros2_ws/src/ecl_core/ecl_containers/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/CMakeLists.txt new file mode 100644 index 0000000..05c1e47 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/CMakeLists.txt @@ -0,0 +1,93 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_containers) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_converters REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_mpl REQUIRED) +find_package(ecl_type_traits REQUIRED) +find_package(ecl_utilities REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + ecl_config::ecl_config + ecl_converters::ecl_converters + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits + ecl_utilities::ecl_utilities +) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_config + ecl_converters + ecl_errors + ecl_exceptions + ecl_formatters + ecl_mpl + ecl_type_traits + ecl_utilities +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_containers/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_containers/doxygen/mainpage.dox new file mode 100644 index 0000000..3f097b1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/doxygen/mainpage.dox @@ -0,0 +1,232 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + +The containers included here are intended to extend the stl containers +in a way that provides features not included in the stl +or to provide alternatives for stl containers that have +been designed for convenience, not speed. Here the emphasis is on +speed first, and c++ conveniences second. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit which +requires this library: + +@code +#include + +// The container types +using ecl::Array; +using ecl::Stencil; +using ecl::FiFo +using ecl::PushAndPop; +@endcode + +These classes are template classes, so no linking is required for these interfaces. + +\section usage Usage + +@subsection fixedArrays Fixed Arrays + +Arrays provide a fixed size container (enabled via a template parameter) +that can be saved as contiguous memory on the stack. This is in contrast to +typical stl containers that are dynamic and thus use the heap for storage, which +is much slower (on my dual-core, often about 10% slower for access methods and +up to 500% slower for construction). + +It provides all the usual stl iterators associated with the object, as well +as many of the access methods excepting the size-changing ones. There are, however +a couple of features of arrays that stand out from stl containers. + +Comma Initialisation + +This concept is brought in (with slightly modified form) from Blitz++ and Eigen. +It enables initialisation via the comma operator. +@code +ecl::Array array; // be careful, at this point, the contents are uninitialised. +array << 1,2,3,4,5; // comma initialisation +@endcode + +Comman initialisers will throw an exception if the range is exceeded in debug mode +(beware release mode!). + +BluePrint Instantiations + +These provide an efficient means of instantiating array classes without a costly +copy-on-the-fly slowdown. It uses a blueprint coupled with what is referred to as a +blueprint factory to do this (refer to ecl_concepts for more details.). +However, the construction makes the usage of this transparent. + +@code +Array array = Array::Constant(3); // construction. +array = Array::Constant(3); // assignment, no costly copy operation used. +@endcode + +@subsection dynamicArrays Dynamic Arrays + +These arrays are almost exactly the same as the former fixed arrays, however they +are dynamically sizeable (though not as automatically nor flexibly as vectors) with their +storage on the heap, not the stack. The lack of flexibility isn't a serious disadvantage +as a control program should generally manage vector memory careful (read, manually!) +anyway. Their other feature is again, like the fixed arrays, the comma initialiser. + +@code +Array array1; // Note the similarity to fixed arrays - no storage allocated with this constructor! +Array array2(4); // Initialise a vector with storage space for four integers. +Array array3 = Array::Constant(4,3); // Initialise space for four integers filled with a value of 3. + +array1.clear(); // Clear - blows away the previous contents and leaves the buffer pointing to NULL. +array1.resize(10); // Resize - blows away previous contents and leaves values uninitialised. +@endcode + +@subsection bufferOverflowSection Buffer Overflow Detection + +Arrays also provide a feature to allow for buffer overflow checking - for both fixed and dynamic arrays. +Often programs pull pointers to various elements on the contiguous array (especially +in really low level routines like vision routines), it is important to know when the stack or heap is +being under or over run. Such functionality can be enabled by declaring the ECL_MEM_CHECK_ARRAYS +macro when compiling (maybe later I'll bring this in as a template parameter). + +Internally, this entails pre/appending some magic characters to the underlying array and then +occasionally performing manual checks to ensure that the magic chars haven't been disturbed. + +@code +#define ECL_MEM_CHECK_ARRAYS + +Array array; array << 1, 2, 3, 4; +while ( control_loop_running ) { + + int* istart = array[0]; + + // send istart off to do some work elsewhere, possibly overrunning or underrunning. + // ... + + if ( array.bufferUnderRun() ) { std::cout << "WARNING! We have an underrun problem houston!" << std::endl; } + if ( array.bufferOverRun() ) { std::cout << "WARNING! We have an overrun problem houston!" << std::endl; } + if ( array.bufferOverFlow() ) { std::cout << "WARNING! We have an unknown problem houston!" << std::endl; } +} +@endcode + +@subsection Stencils + +Often you require a window onto a container (array) and stencils provide a safe way to do this. It +avoids the use of dangerous pointers which can cause problems if the underlying container +goes out of scope or is resized. It does this by including the underlying container as a +reference and also includes similar out of range checks that arrays perform (exception throwing +in debug mode for [] and always for at()). + +@code +typedef Array FixedArray; +typedef Stencil< FixedArray > FixedStencil; + +FixedArray array; +array << 1,2,3,4,5; +FixedStencil stencil(array,1,3); // windows from index 1 to 3 +std::cout << stencil[1] << std::endl; // accesses array[2]; +@endcode + +@subsection Fifo + +During the construction of fifo, typically length of buffer may be important. + +@code +FiFo fifo(4); // reserved only (not filled) +fifo.push_back( data_incoming ); +@endcode + +An initialised buffer can be important in variaous situation. For example, if you wish +to calculate a moving average, you should wait for N (length of buffer) pieces of +incoming of data. However, if you initialise the whole buffer as above, you can +proceed immediately. + +@code +FiFo fifo_initialised(4, initial_value); // reserved and filled +fifo.push_back( next_data ); // set next data +// ... // calculate the average here +@endcode + +@subsection converters Byte Array Converters + +Some converters utilising ecl::converters::FromByteArray are enabled for arrays and stencils respectively. +These allow conversion to integers of any time from a corresponding, little endian filled +array/stencil of chars. + +@code +typedef Array ByteArray; +ByteArray byte_array; +byte_array << 0x01, 0x02, 0x03; +ecl::Converter toInt; +std::cout << "Conversion: " << toInt(byte_array) << std::endl; // results in 197121 +std::cout << "Conversion: " << toInt(byte_array.stencil(0,2)) << std::endl; // only first two bytes -> 513 +@endcode + +and going the other way, we pass it the byte array for storage when converting (works on both +arrays and stencils)... + +@code +Array byte_array = Array::Constant(0x00); +Stencil< Array > stencil = byte_array.stencil(2,4); +ecl::Converter< Stencil< Array >, ecl::int32 > fromInt; +fromInt(stencil, ecl::int32(197121)); +std::cout << byte_array << std::endl; // 0x00, 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, ... +std::cout << stencil << std::endl; // 0x01, 0x02, 0x03, 0x00 +@endcode + +@subsection Formatters + +Currently there is only formatters for the array and stencil classes classes which do: + +- precision/width formatting for float arrays. +- hex formatting for byte arrays (signed char/char/unsigned char). +- default formatting for other types of arrays (provided they have the required Format for the element type). +- formatting extends to stencils operating on the array. + +@code +#include + +Array::Formatter format; +Array array; +array << 0x01, 0x02, 0x03, 0x04; +std::cout << format(array) << std::endl; +// OR +#include +#include + +Format< Array > format; +Array array; +array << 0x01, 0x02, 0x03, 0x04; +std::cout << format(array) << std::endl; +@endcode + +\section utilities Examples + +- src/examples/array_formatters.cpp + +\section unitTests Unit Tests + +- src/test/arrays.cpp +- src/test/arrays_mem_check.cpp +- src/test/converters.cpp +- src/test/stencil.cpp +- src/test/fifo.cpp + +\section utilities Utilities + +- /ecl_benchmarks/src/bench_containers.cpp : benchmarks various container latencies. + +\section ChangeLog + +- Mar 11 : finally got the byte array converters working properly. +- Sep 10 : moved the container formatter classes here from ecl_formatters. +- Aug 10 : Converter for a byte array (char) to integral type converter. +- Aug 10 : @ref ecl::FiFo "FiFo" provides a simple rotating array. +- Mar 10 : @ref ecl::Stencil "Stencils" provides a safe means to open a window on top of an underlying container. +- Jan 10 : @ref ecl::Array "Arrays" can do buffer overflow checking using ECL_MEM_CHECK_ARRAYS. +- May 09 : @ref ecl::Array "Dynamic Arrays" on the heap with a few bells and whistles. +- May 09 : @ref ecl::blueprints::ConstantArray "Constant Array" : blueprints for arrays filled with a single value. +- May 09 : @ref ecl::Array "Fixed Arrays" on the stack with a few bells and whistles. + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_containers/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_containers/doxygen/namespaces.dox new file mode 100644 index 0000000..63ee986 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/doxygen/namespaces.dox @@ -0,0 +1,34 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::blueprints + * + * @brief Blueprints and factories classes used to generate blueprints (do not use directly). + * + * The blueprints are used to generate lightweight classes that store the rules to + * instantiate or configure classes in this package. These are used internally by + * container classes via inheritance and typedef'd notation for convenience, so you + * should never need to directly use these classes. + **/ +/** + * @namespace ecl::containers + * + * @brief Supporting elements and interfaces for ecl containers. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ +/** + * @namespace ecl::formatters + * + * @brief Supporting classes for container formatters (do not use directly). + * + * Do not use these directly, they are better accessed via the Container::Formatter + * or Format< Container > mechanisms. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..3eb9823 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(containers) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers.hpp new file mode 100644 index 0000000..ed2f084 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/containers.hpp + * + * @brief High-performance or convenience containers not included in the stl. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_HPP_ +#define ECL_CONTAINERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "containers/definitions.hpp" +#include "containers/initialiser.hpp" +#include "containers/array.hpp" +#include "containers/converters.hpp" +#include "containers/fifo.hpp" +#include "containers/push_and_pop.hpp" +#include "containers/stencil.hpp" + +#endif /* ECL_CONTAINERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/CMakeLists.txt new file mode 100644 index 0000000..ce57d81 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/CMakeLists.txt @@ -0,0 +1,17 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(common) +add_subdirectory(array) +add_subdirectory(push_and_pop) +add_subdirectory(stencil) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/containers) + diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array.hpp new file mode 100644 index 0000000..c4e19ba --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array.hpp @@ -0,0 +1,30 @@ +/** + * @file /include/ecl/containers/array.hpp + * + * @brief Fixed size containers with a few bells and whistles. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_HPP_ +#define ECL_CONTAINERS_ARRAY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#ifdef ECL_MEM_CHECK_ARRAYS + #include "array/array_mem_check.hpp" + #include "array/array_dynamic_mem_check.hpp" +#else + #include "array/array_no_mem_check.hpp" + #include "array/array_dynamic_no_mem_check.hpp" +#endif +// make sure the utility classes get included. +#include "array/converters.hpp" +#include "array/formatters.hpp" + +#endif /* ECL_CONTAINERS_ARRAY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/CMakeLists.txt new file mode 100644 index 0000000..7569562 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/containers/array) diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_mem_check.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_mem_check.hpp new file mode 100644 index 0000000..6c36486 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_mem_check.hpp @@ -0,0 +1,746 @@ +/** + * @file /include/ecl/containers/array/array_dynamic_mem_check.hpp + * + * @brief Dynamically sized containers with a few bells and whistles. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_DYNAMIC_MEM_CHECK_HPP_ +#define ECL_CONTAINERS_ARRAY_DYNAMIC_MEM_CHECK_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../definitions.hpp" +#include "../initialiser.hpp" +#include "../stencil.hpp" +#include "array_mem_check.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +template class Array; + +namespace blueprints { + +template class ConstantDynamicArray; + +} // namespace blueprints + +namespace formatters { + +template class ArrayFormatter; + +} // namespace formatters + +/** + * @brief Blueprint factory for dynamic arrays. + * + * Generates various blueprints that instantiate or configure dynamic arrays from commonly + * used algorithms. + * + * @sa @ref ecl::Array "Array". + */ +template +class ECL_PUBLIC BluePrintFactory< Array > { + public: + /** + * @brief Generates a constant array of the specified size. + * + * Generates a blueprint for creating a dynamically sizeable array with + * a constant value of the specified size. + * + * @return ConstantDynamicArray : the resulting blueprint. + */ + static blueprints::ConstantDynamicArray Constant(size_t size, const Type &value) { + return blueprints::ConstantDynamicArray(size,value); + } + virtual ~BluePrintFactory() {}; +}; + +/***************************************************************************** +** Interface [Array][Dynamic] +*****************************************************************************/ +/** + * @brief Dynamic size container with a few bells and whistles. + * + * This is a specialisation of the fixed array class (for size = 0), but + * instead reserves memory dynamically at run-time (on the heap, not the stack). + * Consequently, it is more convenient, but slower than the fixed size array class. + * + * Comparisons: + * + * This class doesn't do resizing on the fly like the stl vector does. It could + * be argued that this makes it less convenient, but the control programmer + * should be manually managing the resizing of the vector anyway (without doing this + * behaviour will be slower and more unpredictable). So this is not really + * a disadvantage. + * + * On the plus side, like the fixed size array, it utilises the comma initialiser. + * + * Usage: + * + * This initialises like the fixed size array, but without the size template parameter. + * Instead, size is managed either through a constructor argument or via one of the + * storage commands. + * + * @code + * Array array; // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * Every other facility that is available with fixed size arrays is also available with this class. + * + * Error Handling + * + * Arrays will throw exceptions whenever an operation performs an out of range operation. + * For most operations, this will only occur in debug mode, so release mode will run + * at full speed. The only exception to this is the accessor function, which provides + * a handle that will always throw if safety is always required. + * + * @code + * int i = array[2]; // If NDEBUG is not defined, this will throw if you exceed the range. + * int i = array.at(2); // This will always throw if you exceed the range. + * @endcode + * + * @tparam Type : the type of the element stored in the array. + * + * @sa @ref ecl::Array "Array". + **/ +template +class ECL_PUBLIC Array : public BluePrintFactory< Array > { + public: + /********************* + ** Typedefs + **********************/ + typedef Type value_type; /**< Array's element type. **/ + typedef Type* iterator; /**< Array's iterator type. **/ + typedef const Type* const_iterator; /**< Array's constant iterator type. **/ + typedef Type& reference; /**< Array's element reference type. **/ + typedef const Type& const_reference; /**< Array's element const reference type. **/ + typedef std::size_t size_type; /**< Array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< Array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< Array's constant reverse iterator type. **/ + typedef formatters::ArrayFormatter Formatter; /**< @brief Formatter for this class. **/ + + /** @brief Generates blueprints for this class. **/ + typedef BluePrintFactory< Array > Factory; + + /********************* + ** Constructors + **********************/ + /** + * @brief Default constructor. + * + * Does not reserve any storage for the array. Just creates the container object. + */ + explicit Array() : buffer_size(0), underrun(NULL), buffer(NULL), overrun(NULL) {} + /** + * @brief Reserves storage for the array. + * + * This simply creates a buffer of the requested size on the heap. + * The values are left uninitialised. + * + * @param reserve_size : the number of elements to be allocated to the container. + */ + explicit Array(const unsigned int reserve_size) : + buffer_size(reserve_size), + underrun(NULL), + buffer(NULL), + overrun(NULL) + { + underrun = (char*) malloc(buffer_size*sizeof(Type)+bufferUnderrunLength()+bufferOverrunLength()); + ecl_assert_throw(underrun != NULL, StandardException(LOC,MemoryError,"Failed to allocate memory to the dynamic array.")); + buffer = (Type*) (underrun+bufferUnderrunLength()); + overrun = (char*) underrun+bufferUnderrunLength()+buffer_size*sizeof(Type); + // Leave it uninitialised, just like eigen containers...faster +// for ( unsigned int i = 0; i < buffer_size; ++i ) { +// buffer[i] = Type(); +// } + initialiseMagicSections(); + }; + /** + * @brief Copy constructor. + * + * This accepts another dynamic array and uses the stl to copy over the contents. + * + * @param array : the array to copy from. + */ + Array(const Array& array) : buffer_size(0), underrun(NULL), buffer(NULL), overrun(NULL) { + if ( array.size() != 0 ) { + resize(array.size()); // not really optimal as we do a fill in resize and then copy here, but its debug version anyway. + std::copy(array.begin(),array.end(),begin()); + } + } + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * Array array = Array::Constant(3,4); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * Array array; + * array = Array::Constant(3,4); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprint concept (refer to ecl_concepts documentation). + * + * @param blueprint : the blue print to use to generate this instance. + */ + template + Array(const blueprints::ArrayBluePrint< T > &blueprint) : buffer_size(0), underrun(NULL), buffer(NULL), overrun(NULL) { + // Note we're using a partially specialised parent interface here otherwise the + // constructor that reserves sizes as well as the comma initialiser won't + // conveniently convert types correctly + // (e.g. Array array(4); array = 1,2,3,4; will fail) + ecl_compile_time_concept_check(BluePrintConcept); + blueprint.implementApply(*this); + initialiseMagicSections(); + } + /** + * @brief Default destructor. + * + * It cleans up the memory that was used on the heap. + **/ + ~Array() { + + if ( underrun != NULL ) { + free(underrun); + } + underrun = NULL; + buffer = NULL; + overrun = NULL; + } + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * Array array(4); // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<<(const Type &value) { + return containers::BoundedListInitialiser(value,buffer,buffer_size); + } + + void operator=(const Array& array) { + if ( array.size() == 0 ) { + clear(); + } else { + resize(array.size()); // not really optimal as we do a fill in resize and then copy here, but its debug version anyway. + std::copy(array.begin(),array.end(),begin()); + } + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the array. + * @return iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator begin() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer; + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator begin() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer; + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator end() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer+buffer_size; + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator end() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer+buffer_size; + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rbegin() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rbegin() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rend() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rend() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return const_reverse_iterator(begin()); + } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reference front() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[0]; + } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reference front() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[0]; + } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reference back() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[buffer_size-1]; + } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reference back() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[buffer_size-1]; + } + + /********************* + ** Accessors + **********************/ + /** + * @brief Open a window (stencil) onto the array. + * + * Opens a window onto the array, providing a similar container-like class to manipulate. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil< Array > stencil(const unsigned int& start_index, const unsigned int& n) { + ecl_assert_throw(start_index < size(), StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying array size.")); + ecl_assert_throw(start_index+n <= size(), StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying array size.")); + return Stencil< Array >(*this, begin()+start_index, begin()+start_index+n); + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) { + ecl_assert_throw( i=buffer_size ) { + throw StandardException(LOC,OutOfRangeError); + } + return buffer[i]; + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const { + if ( i>=buffer_size ) { + throw StandardException(LOC,OutOfRangeError); + } + return buffer[i]; + } + + /********************* + ** Utilities + **********************/ + /** + * @brief The size of the array. + * + * Returns the current (dynamic) size of the array. + * + * @return size_type : the size of the array. + */ + size_type size() const { return buffer_size; } + + /** + * @brief Resize the array, clearing whatever was in there before. + * + * This resizes the array. Take care with this as it will clear whatever was + * previously stored in the buffer. All values are uninitialised after clearing. + * + * @param n : the new size to be allocated for the array. + */ + void resize( size_t n ) { + if ( underrun != NULL ) { + free(underrun); + } + buffer_size = n; + underrun = (char*) malloc(buffer_size*sizeof(Type)+bufferUnderrunLength()+bufferOverrunLength()); + ecl_assert_throw(underrun != NULL, StandardException(LOC,MemoryError,"Failed to allocate memory to the dynamic array.")); + buffer = (Type*) (underrun+bufferUnderrunLength()); + overrun = (char*) underrun+bufferUnderrunLength()+buffer_size*sizeof(Type); + // Leave it uninitialised, just like eigen containers...faster +// for ( unsigned int i = 0; i < buffer_size; ++i ) { +// buffer[i] = Type(); +// } + initialiseMagicSections(); + } + /** + * @brief Clear the array, deleting all storage space previously allocated. + * + * Clear the array, deleting all storage space previously allocated. + */ + void clear() { + if ( underrun != NULL ) { + free(underrun); + underrun = NULL; + buffer = NULL; + overrun = NULL; + } + buffer_size = 0; + } + + /********************* + ** Streaming + **********************/ + /** + * Insertion operator for sending the array to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param array : the array to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Array &array); + + /****************************************** + ** Buffer under/overrun checks + *******************************************/ + bool bufferUnderRun(); + bool bufferOverRun(); + bool bufferOverFlow(); + + private: + void initialiseMagicSections(); + + static const unsigned int& bufferOverrunLength() { + static const unsigned int buffer_overrun_length = 4; + return buffer_overrun_length; + } + static const unsigned int& bufferUnderrunLength() { + static const unsigned int buffer_underrun_length = 4; + return buffer_underrun_length; + } + static const char& magicChar() { + static const char magic_char = static_cast(0xCC); + return magic_char; + } + unsigned int buffer_size; + char *underrun; + Type *buffer; + char *overrun; +}; + +/***************************************************************************** +** Implementation [Array][MemCheck] +*****************************************************************************/ +/** + * @brief Prepares the array for overrun and underrun detection. + * + * Initialise the under and overrun sections with a magic char. This is later + * checked to see if its been disturbed. + */ +template +void Array::initialiseMagicSections() { + + // Should check that buffer != NULL here, but this isn't user API so just have to guarantee it internally. + for ( unsigned int i = 0; i < bufferUnderrunLength(); ++i ) { + *(underrun+i) = magicChar(); + } + for ( unsigned int i = 0; i < bufferOverrunLength(); ++i ) { + *(overrun+i) = magicChar(); + } +} +/** + * @brief Manual handle to check for buffer underruns. + * + * This checks the magic chars prepended to the underlying c array. If + * the magic chars have been modified, then this signals a warning that + * an under/overrun has occurred. + * @return bool : true if a buffer underrun is detected, false otherwise. + */ +template +bool Array::bufferUnderRun() { + if ( underrun != NULL ) { + for ( unsigned int i = 0; i < bufferUnderrunLength(); ++i ) { + if ( *(underrun+i) != magicChar() ) { + return true; + } + } + } + return false; +} +/** + * @brief Manual handle to check for buffer overruns. + * + * This checks the magic chars appended to the underlying c array. If + * the magic chars have been modified, then this signals a warning that + * an under/overrun has occurred. + * + * @return bool : true if a buffer overrun is detected, false otherwise. + */ +template +bool Array::bufferOverRun() { + + if ( overrun != NULL ) { + for ( unsigned int i = 0; i < bufferOverrunLength(); ++i ) { + if ( *(overrun+i) != magicChar() ) { + return true; + } + } + } + return false; +} + +/** + * @brief Manual handle to check for buffer under/over runs simultaneously. + * + * This performs both under and overrun checks. If an overflow has + * occured, this returns the status but does not exactly specify + * if it was an underrun or overrun. + * + * @return bool : true if a buffer overflow is detected, false otherwise. + */ +template +bool Array::bufferOverFlow() { + return ( bufferOverRun() || bufferUnderRun() ); +} + + +/***************************************************************************** +** Implementation [Array] +*****************************************************************************/ + +template +OutputStream& operator<<(OutputStream &ostream , const Array &array) { + + ostream << "[ "; + for(size_t i = 0; i < array.buffer_size; ++i ) + { + ostream << array[i] << " "; + } + ostream << "]"; + ostream.flush(); + + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [ConstantDynamicArray] +*****************************************************************************/ + +/** + * @brief Blueprint for generating a cubic spline satisfying C2 constraints. + * + * Generates a blueprint for creating cubic splines on a set of data + * satisfying a heuristic that automatically generates y' values at the + * via points. + **/ +template +class ConstantDynamicArray: public ArrayBluePrint< ConstantDynamicArray > { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::Array base_type; + /** + * @brief Default constructor. + * + * Default constructor (only utilised by the blueprint compile time assert). + */ + ConstantDynamicArray() {}; + + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * This constructor saves the input parameters to use when generating the + * instance later. + * + * @param size : the size of the array to create. + * @param value : the constant value to fill the array with (defaults to zero). + */ + ConstantDynamicArray(size_t size, const Type &value ) : + reserve_size(size), + val(value) + {} + + virtual ~ConstantDynamicArray() {}; + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new array configured with a constant value. Take care + * not to use this in assignment, as it will do a costly copy of the entire + * array. It is, however, fine to use when constructing as the copy + * constructor will simply use this copy for the constructing object. + * + * @return Array : a copy of the array. + */ + base_type instantiate() { + ecl::Array array(reserve_size); + std::fill_n(array.begin(),reserve_size,val); + return array; + } + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Fill all elements of an existing array with a constant value. + * Note that this clears whatever was initially in the array. + * + * @param array : the array to fill. + */ + void apply(base_type& array) const { + array.resize(reserve_size); + std::fill_n(array.begin(),reserve_size,val); + } + + private: + size_t reserve_size; + Type val; +}; + +} // namespace blueprints +} // namespace ecl + + +#endif /* ECL_CONTAINERS_ARRAY_DYNAMIC_MEM_CHECK_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_no_mem_check.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_no_mem_check.hpp new file mode 100644 index 0000000..539443d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_dynamic_no_mem_check.hpp @@ -0,0 +1,626 @@ +/** + * @file /include/ecl/containers/array/array_dynamic_no_mem_check.hpp + * + * @brief Dynamically sized containers with a few bells and whistles. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_DYNAMIC_NO_MEM_CHECK_HPP_ +#define ECL_CONTAINERS_ARRAY_DYNAMIC_NO_MEM_CHECK_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../definitions.hpp" +#include "../initialiser.hpp" +#include "../stencil.hpp" +#include "array_no_mem_check.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +template class Array; + +namespace blueprints { + +template class ConstantDynamicArray; + +} // namespace blueprints + +namespace formatters { + +template class ArrayFormatter; + +} // namespace formatters + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ +/** + * @brief Blueprint factory for dynamic arrays. + * + * Generates various blueprints that instantiate or configure dynamic arrays from commonly + * used algorithms. + * + * @sa @ref ecl::Array "Array". + */ +template +class ECL_PUBLIC BluePrintFactory< Array > { + public: + /** + * @brief Generates a constant array of the specified size. + * + * Generates a blueprint for creating a dynamically sizeable array with + * a constant value of the specified size. + * + * @return ConstantDynamicArray : the resulting blueprint. + */ + static blueprints::ConstantDynamicArray Constant(size_t size, const Type &value) { + return blueprints::ConstantDynamicArray(size,value); + } + virtual ~BluePrintFactory() {}; +}; + +/***************************************************************************** +** Interface [Array][Dynamic] +*****************************************************************************/ +/** + * @brief Dynamic size container with a few bells and whistles. + * + * This is a specialisation of the fixed array class (for size = 0), but + * instead reserves memory dynamically at run-time (on the heap, not the stack). + * Consequently, it is more convenient, but slower than the fixed size array class. + * + * Comparisons: + * + * This class doesn't do resizing on the fly like the stl vector does. It could + * be argued that this makes it less convenient, but the control programmer + * should be manually managing the resizing of the vector anyway (without doing this + * behaviour will be slower and more unpredictable). So this is not really + * a disadvantage. + * + * On the plus side, like the fixed size array, it utilises the comma initialiser. + * + * Usage: + * + * This initialises like the fixed size array, but without the size template parameter. + * Instead, size is managed either through a constructor argument or via one of the + * storage commands. + * + * @code + * Array array; // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * Every other facility that is available with fixed size arrays is also available with this class. + * + * Error Handling + * + * Arrays will throw exceptions whenever an operation performs an out of range operation. + * For most operations, this will only occur in debug mode, so release mode will run + * at full speed. The only exception to this is the accessor function, which provides + * a handle that will always throw if safety is always required. + * + * @code + * int i = array[2]; // If NDEBUG is not defined, this will throw if you exceed the range. + * int i = array.at(2); // This will always throw if you exceed the range. + * @endcode + * + * @tparam Type : the type of the element stored in the array. + * + * @sa @ref ecl::Array "Array". + **/ +template +class ECL_PUBLIC Array : public BluePrintFactory< Array > { + public: + /********************* + ** Typedefs + **********************/ + typedef Type value_type; /**< Array's element type. **/ + typedef Type* iterator; /**< Array's iterator type. **/ + typedef const Type* const_iterator; /**< Array's constant iterator type. **/ + typedef Type& reference; /**< Array's element reference type. **/ + typedef const Type& const_reference; /**< Array's element const reference type. **/ + typedef std::size_t size_type; /**< Array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< Array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< Array's constant reverse iterator type. **/ + typedef formatters::ArrayFormatter Formatter; /**< @brief Formatter for this class. **/ + + /** @brief Generates blueprints for this class. **/ + typedef BluePrintFactory< Array > Factory; + + /********************* + ** Constructors + **********************/ + /** + * @brief Default constructor. + * + * Does not reserve any storage for the array. Just creates the container object. + */ + explicit Array() : buffer_size(0), buffer(NULL) {} + /** + * @brief Reserves storage for the array. + * + * This simply creates a buffer of the requested size on the heap. + * The values are left uninitialised. + * + * @param reserve_size : the number of elements to be allocated to the container. + */ + explicit Array(const unsigned int reserve_size) : buffer_size(reserve_size), buffer(NULL) { + buffer = new Type[reserve_size]; + }; + /** + * @brief Copy constructor. + * + * This accepts another dynamic array and uses the stl to copy over the contents. + * + * @param array : the array to copy from. + */ + Array(const Array& array) : + Factory(), + buffer_size(0), + buffer(NULL) + { + if ( array.size() != 0 ) { + resize(array.size()); + std::copy(array.begin(),array.end(),begin()); + } + } + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * Array array = Array::Constant(3,4); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * Array array; + * array = Array::Constant(3,4); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprint concept (refer to ecl_concepts documentation). + * + * @param blueprint : the blue print to use to generate this instance. + */ + template + Array(const blueprints::ArrayBluePrint< T > &blueprint) : buffer_size(0), buffer(NULL) { + // Note we're using a partially specialised parent interface here otherwise the + // constructor that reserves sizes as well as the comma initialiser won't + // conveniently convert types correctly + // (e.g. Array array(4); array = 1,2,3,4; will fail) + ecl_compile_time_concept_check(BluePrintConcept); + blueprint.implementApply(*this); + } + /** + * @brief Default destructor. + * + * It cleans up the memory that was used on the heap. + **/ + ~Array() { + if ( buffer != NULL ) { + delete[] buffer; + } + } + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * Array array(4); // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<<(const Type &value) { + return containers::BoundedListInitialiser(value,buffer,buffer_size); + } + + void operator=(const Array& array) { + if ( array.size() == 0 ) { + clear(); + } else { + resize(array.size()); + std::copy(array.begin(),array.end(),begin()); + } + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the array. + * @return iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator begin() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer; + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator begin() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer; + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator end() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer+buffer_size; + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator end() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer+buffer_size; + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rbegin() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rbegin() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rend() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rend() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return const_reverse_iterator(begin()); + } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reference front() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[0]; + } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reference front() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[0]; + } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reference back() { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[buffer_size-1]; + } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reference back() const { + ecl_assert_throw( buffer != NULL, StandardException(LOC,OutOfRangeError) ); + return buffer[buffer_size-1]; + } + + /********************* + ** Accessors + **********************/ + /** + * @brief Open a window (stencil) onto the array. + * + * Opens a window onto the array, providing a similar container-like class to manipulate. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil< Array > stencil(const unsigned int& start_index, const unsigned int& n) { + ecl_assert_throw(start_index < size(), StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying array size.")); + ecl_assert_throw(start_index+n <= size(), StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying array size.")); + return Stencil< Array >(*this, begin()+start_index, begin()+start_index+n); + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) { + ecl_assert_throw( i=buffer_size ) { + throw StandardException(LOC,OutOfRangeError); + } + return buffer[i]; + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const { + if ( i>=buffer_size ) { + throw StandardException(LOC,OutOfRangeError); + } + return buffer[i]; + } + + /********************* + ** Utilities + **********************/ + /** + * @brief The size of the array. + * + * Returns the current (dynamic) size of the array. + * + * @return size_type : the size of the array. + */ + size_type size() const { return buffer_size; } + + /** + * @brief Resize the array, clearing whatever was in there before. + * + * This resizes the array. Take care with this as it will clear whatever was + * previously stored in the buffer. All values are uninitialised after clearing. + * + * @param n : the new size to be allocated for the array. + */ + void resize( size_t n ) { + if ( buffer != NULL ) { + delete[] buffer; + } + buffer = new Type[n]; + buffer_size = n; + } + /** + * @brief Clear the array, deleting all storage space previously allocated. + * + * Clear the array, deleting all storage space previously allocated. + */ + void clear() { + if ( buffer != NULL ) { + delete[] buffer; + buffer = NULL; + } + buffer_size = 0; + } + + /********************* + ** Streaming + **********************/ + /** + * Insertion operator for sending the array to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param array : the array to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Array &array); + + private: + unsigned int buffer_size; + Type *buffer; + +}; + +/***************************************************************************** +** Implementation [Array] +*****************************************************************************/ + +template +OutputStream& operator<<(OutputStream &ostream , const Array &array) { + + ostream << "[ "; + for(size_t i = 0; i < array.buffer_size; ++i ) + { + ostream << array[i] << " "; + } + ostream << "]"; + ostream.flush(); + + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [ConstantDynamicArray] +*****************************************************************************/ + +/** + * @brief Blueprint for generating a cubic spline satisfying C2 constraints. + * + * Generates a blueprint for creating cubic splines on a set of data + * satisfying a heuristic that automatically generates y' values at the + * via points. + **/ +template +class ConstantDynamicArray: public ArrayBluePrint< ConstantDynamicArray > { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::Array base_type; + /** + * @brief Default constructor. + * + * Default constructor (only utilised by the blueprint compile time assert). + */ + ConstantDynamicArray() {}; + + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * This constructor saves the input parameters to use when generating the + * instance later. + * + * @param size : the size of the array to create. + * @param value : the constant value to fill the array with (defaults to zero). + */ + ConstantDynamicArray(size_t size, const Type &value ) : + reserve_size(size), + val(value) + {} + + virtual ~ConstantDynamicArray() {}; + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new array configured with a constant value. Take care + * not to use this in assignment, as it will do a costly copy of the entire + * array. It is, however, fine to use when constructing as the copy + * constructor will simply use this copy for the constructing object. + * + * @return Array : a copy of the array. + */ + base_type instantiate() { + ecl::Array array(reserve_size); + std::fill_n(array.begin(),reserve_size,val); + return array; + } + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Fill all elements of an existing array with a constant value. + * Note that this clears whatever was initially in the array. + * + * @param array : the array to fill. + */ + void apply(base_type& array) const { + array.resize(reserve_size); + std::fill_n(array.begin(),reserve_size,val); + } + + private: + size_t reserve_size; + Type val; +}; + + +} // namespace blueprints +} // namespace ecl + + +#endif /* ECL_CONTAINERS_ARRAY_DYNAMIC_NO_MEM_CHECK_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_mem_check.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_mem_check.hpp new file mode 100644 index 0000000..d9c53ee --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_mem_check.hpp @@ -0,0 +1,626 @@ +/** + * @file /include/ecl/containers/array/array_mem_check.hpp + * + * @brief Fixed size containers with a few bells and whistles. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_MEM_CHECK_HPP_ +#define ECL_CONTAINERS_ARRAY_MEM_CHECK_HPP_ +#ifdef ECL_MEM_CHECK_ARRAYS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // std::copy +#include // size_t +#include +#include "../definitions.hpp" +#include "../initialiser.hpp" +#include "../stencil.hpp" +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +namespace blueprints { + +template class ArrayFactory; +template class ArrayBluePrint; +template class ConstantArray; + +} // namespace blueprints + +namespace formatters { + +template class ArrayFormatter; + +} // namespace formatters + +/***************************************************************************** +** Interface [Array][Fixed] +*****************************************************************************/ +/** + * @brief Fixed size container with a few bells and whistles. + * + * All of the stl arrays are dynamically sizable, which means they are stored + * on the heap which is generally much slower for access/write operations than + * one which is stored on the stack. However, the stl provides no option for + * a fixed size container which take advantage of this, so this class provides + * that option. Essentially, its simply a fixed size array with a few bells + * and whistles. + * + * Initialisation + * + * We use the comma initialiser (similar to that used in Blitz++ and Eigen2) here + * for convenient initialisation. However there are other mechanisms, the + * most interesting of which is Boost's Array class which uses a normal + * aggregate initialiser (like that of a struct with curly braces). I did + * some tests to compare the performance of both, and both perform similarly. + * Since there was no real difference in performance I chose the comma + * initialiser here as it can also be used after construction and will provide + * a consistent means of initialisation seeing as we also use Eigen in the Math + * module. If you're in for strict c++ layouts, then the comma initialiser also + * lets you hide the base c array as a private member (the aggregate initialiser + * only works when your base c array is a public member). + * + * @code + * Array array; // At this point it is uninitialised. + * array = 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * Error Handling + * + * Arrays will throw exceptions whenever an operation performs an out of range operation. + * For most operations, this will only occur in debug mode, so release mode will run + * at full speed. The only exception to this is the accessor function, which provides + * a handle that will always throw if safety is always required. + * + * @code + * int i = array[2]; // If NDEBUG is not defined, this will throw if you exceed the range. + * int i = array.at(2); // This will always throw if you exceed the range. + * @endcode + * + * @tparam Type : the type of the element stored in the array. + * + * @sa @ref ecl::containers::BoundedListInitialiser "BoundedListInitialiser", @ref ecl::blueprints::ArrayFactory "ArrayFactory". + **/ +template +class ECL_PUBLIC Array : public blueprints::ArrayFactory { + public: + /********************* + ** Typedefs + **********************/ + typedef Type value_type; /**< Array's element type. **/ + typedef Type* iterator; /**< Array's iterator type. **/ + typedef const Type* const_iterator; /**< Array's constant iterator type. **/ + typedef Type& reference; /**< Array's element reference type. **/ + typedef const Type& const_reference; /**< Array's element const reference type. **/ + typedef std::size_t size_type; /**< Array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< Array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< Array's constant reverse iterator type. **/ + typedef blueprints::ArrayFactory Factory; /**< @brief Generates blueprints for this class. **/ + typedef formatters::ArrayFormatter Formatter; /**< @brief Formatter for this class. **/ + + /********************* + ** Constructors + **********************/ + /** + * Default constructor that simply allocates memory, but leaves all the + * element uninitialised. + */ + Array() { initialiseMagicSections(); }; + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation of the array from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the @ref ecl::blueprints::ArrayFactory "BluePrintFactory". + * @code + * Array array = Array::Constant(3); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * Array array; + * array = Array::Constant(3); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprint concept (refer to ecl_concepts documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa @ref ecl::blueprints::ArrayFactory "ArrayFactory". + */ + template + Array(const blueprints::ArrayBluePrint< T > &blueprint) { + ecl_compile_time_concept_check(BluePrintConcept); + blueprint.implementApply(*this); + initialiseMagicSections(); + } + + virtual ~Array() {}; // The user should manually check these in the classes that hold them. + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * Array array; // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<<(const Type &value) { + return containers::BoundedListInitialiser(value,elements); + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the array. + * @return iterator : points to the beginning of the array. + */ + iterator begin() { return elements; } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + */ + const_iterator begin() const { return elements; } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + */ + iterator end() { return elements+Size; } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + */ + const_iterator end() const { return elements+Size; } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + */ + reverse_iterator rbegin() { return reverse_iterator(end()); } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + */ + const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + */ + reverse_iterator rend() { return reverse_iterator(begin()); } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + */ + const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + */ + reference front() { return elements[0]; } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + */ + const_reference front() const { return elements[0]; } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + */ + reference back() { return elements[Size-1]; } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + */ + const_reference back() const { return elements[Size-1]; } + + /********************* + ** Accessors + **********************/ + /** + * @brief Open a window (stencil) onto the array. + * + * Opens a window onto the array, providing a similar container-like class to manipulate. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil< Array > stencil(const unsigned int& start_index, const unsigned int& n) { + ecl_assert_throw(start_index < Size, StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying array size.")); + ecl_assert_throw(start_index+n <= Size, StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying array size.")); + return Stencil< Array >(*this, begin()+start_index, begin()+start_index+n); + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) { + ecl_assert_throw( i=Size ) { + throw StandardException(LOC,OutOfRangeError); + } + return elements[i]; + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const { + if ( i>=Size ) { + throw StandardException(LOC,OutOfRangeError); + } + return elements[i]; + } + + /********************* + ** Utilities + **********************/ + /** + * The size of the array. Since the array storage is fixed, this need only be a static + * method for the whole class. + * @return size_type : the size of the array. + */ + static size_type size() { return Size; } + + /********************* + ** Streaming + **********************/ + /** + * Insertion operator for sending the array to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param array : the array to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Array &array); + + /****************************************** + ** Buffer under/overrun checks + *******************************************/ + bool bufferUnderRun(); + bool bufferOverRun(); + bool bufferOverFlow(); + + private: + void initialiseMagicSections(); + + static const unsigned int& bufferOverrunLength() { + static const unsigned int buffer_overrun_length = 4; + return buffer_overrun_length; + } + static const unsigned int& bufferUnderrunLength() { + static const unsigned int buffer_underrun_length = 4; + return buffer_underrun_length; + } + static const char& magicChar() { + static const char magic_char = static_cast(0xCC); + return magic_char; + } + char underrun[4]; + value_type elements[Size]; + char overrun[4]; +}; + +/***************************************************************************** +** Implementation [Array] +*****************************************************************************/ +/** + * @brief Prepares the array for overrun and underrun detection. + * + * Initialise the under and overrun sections with a magic char. This is later + * checked to see if its been disturbed. + */ +template +void Array::initialiseMagicSections() { + + for ( unsigned int i = 0; i < bufferUnderrunLength(); ++i ) { + underrun[i] = magicChar(); + } + for ( unsigned int i = 0; i < bufferOverrunLength(); ++i ) { + overrun[i] = magicChar(); + } + +} +/** + * @brief Manual handle to check for buffer overruns. + * + * This checks the magic chars appended to the underlying c array. If + * the magic chars have been modified, then this signals a warning that + * an under/overrun has occurred. + * + * @return bool : true if a buffer overrun is detected, false otherwise. + */ +template +bool Array::bufferOverRun() { + + for ( unsigned int i = 0; i < bufferOverrunLength(); ++i ) { + if ( overrun[i] != magicChar() ) { + return true; + } + } + return false; +} + +/** + * @brief Manual handle to check for buffer underruns. + * + * This checks the magic chars prepended to the underlying c array. If + * the magic chars have been modified, then this signals a warning that + * an under/overrun has occurred. + * @return bool : true if a buffer underrun is detected, false otherwise. + */ +template +bool Array::bufferUnderRun() { + for ( unsigned int i = 0; i < bufferUnderrunLength(); ++i ) { + if ( underrun[i] != magicChar() ) { + return true; + } + } + return false; +} +/** + * @brief Manual handle to check for buffer under/over runs simultaneously. + * + * This performs both under and overrun checks. If an overflow has + * occured, this returns the status but does not exactly specify + * if it was an underrun or overrun. + * + * @return bool : true if a buffer overflow is detected, false otherwise. + */ +template +bool Array::bufferOverFlow() { + return ( bufferOverRun() || bufferUnderRun() ); +} + + +/***************************************************************************** +** Implementation [Array][Streaming] +*****************************************************************************/ + +template +OutputStream& operator<<(OutputStream &ostream , const Array &array) { + + ecl_compile_time_concept_check(StreamConcept); + + ostream << "[ "; + for(size_t i = 0; i < ArraySize; ++i ) + { + ostream << array[i] << " "; + } + ostream << "]"; + ostream.flush(); + + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/** + * @brief Parent class for array blueprints. + * + * This parent class for array blueprints is necessary to provide a convenient + * assignment interface to the array class. Without this, no casting to simple + * fundamental types gets done when using the comma initialiser because they + * get locked into a templatised blueprint assignment operator. e.g. + * + * @code + * Array array; + * array = 1,2,3,4; + * @endcode + * This would cause a concept checking compile time error because the first value + * is an integer, not a double. Hence this would be passed to the templatised + * constructor and the concept check would fail. What was intended was that this + * be automatically casted before being sent to the assignment operator for the + * double. + * + * So here we generate a parent class and design the constructor in the Array + * to use that. We don't want to lose speed through virtual calls though, so we + * use the curiously recurring template pattern trick to get us to the goal! + * + * @sa @ref ecl::Array "Array". + */ +template +class ArrayBluePrint { + public: + /** + * A crtp virtual call to its children's instantiate method. The template + * argument is used, because the crtp base cannot catch typedef's in its + * children at this point of the compilation. With the template parameter + * this check is delayed until enough of this base class is known. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @return BaseType : the type to be generated by the blueprint. + */ + template + BaseType implementInstantiate() { + return static_cast(this)->instantiate(); + } + /** + * A crtp virtual call to its children's apply method. This acts on the + * blueprint's target class to configure it according to the blueprint. + * The template parameter is a trick to delay the determination of the + * target type, because at this point of the compilation it cannot + * retrieve the base_type from the derived type. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @param array : the underlying array to be configured. + */ + template + void implementApply(BaseType& array) const { + static_cast(this)->apply(array); + } + + virtual ~ArrayBluePrint() {} +}; +/** + * @brief Blueprint for instantiating/configuring an array filled with a constant. + * + * Implements the BluePrint concept for instantiating/configuring an array + * filled with a constant. + * + * @sa @ref ecl::Array "Array". + */ +template +class ConstantArray : public ArrayBluePrint< ConstantArray > { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::Array base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * This constructor saves the input parameters to use when generating the + * instance later. + * + * @param value : the constant value to fill the array with (defaults to zero). + */ + ConstantArray(const Type& value = 0) : val(value) {} + + virtual ~ConstantArray() {}; + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new array configured with a constant value. Take care + * not to use this in assignment, as it will do a costly copy of the entire + * array. It is, however, fine to use when constructing as the copy + * constructor will simply use this copy for the constructing object. + * + * @return Array : a copy of the array. + */ + base_type instantiate() { + ecl::Array array; + std::fill_n(array.begin(),Size,val); + return array; + } + + /** + * Fill all elements of an existing array with a constant value. + * @param array : the array to fill. + */ + void apply(base_type& array) const { + std::fill_n(array.begin(),Size,val); + } + + private: + const Type& val; +}; + +/** + * @brief BluePrint factory for the @ref ecl::Array "Array" class. + * + * Generates various blueprints that instantiate or configure arrays with + * commonly used configurations. + * + * @sa @ref ecl::Array "Array". + */ +template +class ArrayFactory { + public: + /** + * Generates a blueprint for creating constant arrays. The array constructor + * and assignment operator handle the usage of the blueprint from there. + * @param value : the value to fill the array with. + * @return ConstantArray : a blueprint for generating or configuring a constant array. + */ + static ConstantArray Constant(const Type& value) { + return ConstantArray(value); + } + + virtual ~ArrayFactory() {}; +}; + +} // namespace blueprints +} // namespace ecl + +#endif /* ECL_MEM_CHECK_ARRAYS */ +#endif /* ECL_CONTAINERS_ARRAY_MEM_CHECK_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_no_mem_check.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_no_mem_check.hpp new file mode 100644 index 0000000..9f3562f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/array_no_mem_check.hpp @@ -0,0 +1,532 @@ +/** + * @file /include/ecl/containers/array/array_no_mem_check.hpp + * + * @brief Fixed size containers with a few bells and whistles. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_NO_MEM_CHECK_HPP_ +#define ECL_CONTAINERS_ARRAY_NO_MEM_CHECK_HPP_ +#ifndef ECL_MEM_CHECK_ARRAYS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // std::copy +#include // size_t +#include +#include "../definitions.hpp" +#include "../initialiser.hpp" +#include "../stencil.hpp" +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +namespace blueprints { + +template class ArrayFactory; +template class ArrayBluePrint; +template class ConstantArray; + +} // namespace blueprints + +namespace formatters { + +template class ArrayFormatter; + +} // namespace formatters + +/***************************************************************************** +** Interface [Array][Fixed] +*****************************************************************************/ +/** + * @brief Fixed size container with a few bells and whistles. + * + * All of the stl arrays are dynamically sizable, which means they are stored + * on the heap which is generally much slower for access/write operations than + * one which is stored on the stack. However, the stl provides no option for + * a fixed size container which take advantage of this, so this class provides + * that option. Essentially, its simply a fixed size array with a few bells + * and whistles. + * + * Initialisation + * + * We use the comma initialiser (similar to that used in Blitz++ and Eigen2) here + * for convenient initialisation. However there are other mechanisms, the + * most interesting of which is Boost's Array class which uses a normal + * aggregate initialiser (like that of a struct with curly braces). I did + * some tests to compare the performance of both, and both perform similarly. + * Since there was no real difference in performance I chose the comma + * initialiser here as it can also be used after construction and will provide + * a consistent means of initialisation seeing as we also use Eigen in the Math + * module. If you're in for strict c++ layouts, then the comma initialiser also + * lets you hide the base c array as a private member (the aggregate initialiser + * only works when your base c array is a public member). + * + * @code + * Array array; // At this point it is uninitialised. + * array = 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * Error Handling + * + * Arrays will throw exceptions whenever an operation performs an out of range operation. + * For most operations, this will only occur in debug mode, so release mode will run + * at full speed. The only exception to this is the accessor function, which provides + * a handle that will always throw if safety is always required. + * + * @code + * int i = array[2]; // If NDEBUG is not defined, this will throw if you exceed the range. + * int i = array.at(2); // This will always throw if you exceed the range. + * @endcode + * + * @tparam Type : the type of the element stored in the array. + * + * @sa @ref ecl::containers::BoundedListInitialiser "BoundedListInitialiser", @ref blueprints::ArrayFactory "ArrayFactory". + **/ +template +class ECL_PUBLIC Array : public blueprints::ArrayFactory { + public: + /********************* + ** Typedefs + **********************/ + typedef Type value_type; /**< Array's element type. **/ + typedef Type* iterator; /**< Array's iterator type. **/ + typedef const Type* const_iterator; /**< Array's constant iterator type. **/ + typedef Type& reference; /**< Array's element reference type. **/ + typedef const Type& const_reference; /**< Array's element const reference type. **/ + typedef std::size_t size_type; /**< Array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< Array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< Array's constant reverse iterator type. **/ + typedef blueprints::ArrayFactory Factory; /**< @brief Generates blueprints for this class. **/ + typedef formatters::ArrayFormatter Formatter; /**< @brief Formatter for this class. **/ + + /********************* + ** Constructors + **********************/ + /** + * Default constructor that simply allocates memory, but leaves all the + * element uninitialised. + */ + Array() {}; + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation of the array from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the @ref ecl::blueprints::ArrayFactory "BluePrintFactory". + * @code + * Array array = Array::Constant(3); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * Array array; + * array = Array::Constant(3); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprint concept (refer to ecl_concepts documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa @ref ecl::blueprints::ArrayFactory "ArrayFactory". + */ + template + Array(const blueprints::ArrayBluePrint< T > &blueprint) { + ecl_compile_time_concept_check(BluePrintConcept); + blueprint.implementApply(*this); + } + + virtual ~Array() {}; + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * Array array; // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<<(const Type &value) { + return containers::BoundedListInitialiser(value,elements); + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the array. + * @return iterator : points to the beginning of the array. + */ + iterator begin() { return elements; } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + */ + const_iterator begin() const { return elements; } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + */ + iterator end() { return elements+Size; } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + */ + const_iterator end() const { return elements+Size; } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + */ + reverse_iterator rbegin() { return reverse_iterator(end()); } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + */ + const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + */ + reverse_iterator rend() { return reverse_iterator(begin()); } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + */ + const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + */ + reference front() { return elements[0]; } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + */ + const_reference front() const { return elements[0]; } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + */ + reference back() { return elements[Size-1]; } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + */ + const_reference back() const { return elements[Size-1]; } + + /********************* + ** Accessors + **********************/ + /** + * @brief Open a window (stencil) onto the array. + * + * Opens a window onto the array, providing a similar container-like class to manipulate. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil< Array > stencil(const unsigned int& start_index, const unsigned int& n) { + ecl_assert_throw(start_index < Size, StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying array size.")); + ecl_assert_throw(start_index+n <= Size, StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying array size.")); + return Stencil< Array >(*this, begin()+start_index, begin()+start_index+n); + } + + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) { + ecl_assert_throw( i=Size ) { + throw StandardException(LOC,OutOfRangeError); + } + return elements[i]; + } + /** + * Accesses elements in the array, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const { + if ( i>=Size ) { + throw StandardException(LOC,OutOfRangeError); + } + return elements[i]; + } + + /********************* + ** Utilities + **********************/ + /** + * The size of the array. Since the array storage is fixed, this need only be a static + * method for the whole class. + * @return size_type : the size of the array. + */ + static size_type size() { return Size; } + + /********************* + ** Streaming + **********************/ + /** + * Insertion operator for sending the array to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param array : the array to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Array &array); + + private: + value_type elements[Size]; +}; + +/***************************************************************************** +** Implementation [Array][Insertion Operators] +*****************************************************************************/ + +template +OutputStream& operator<<(OutputStream &ostream , const Array &array) { + + ecl_compile_time_concept_check(StreamConcept); + + ostream << "[ "; + for(size_t i = 0; i < ArraySize; ++i ) + { + ostream << array[i] << " "; + } + ostream << "]"; + ostream.flush(); + + return ostream; +} + + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/** + * @brief Parent class for array blueprints. + * + * This parent class for array blueprints is necessary to provide a convenient + * assignment interface to the array class. Without this, no casting to simple + * fundamental types gets done when using the comma initialiser because they + * get locked into a templatised blueprint assignment operator. e.g. + * + * @code + * Array array; + * array = 1,2,3,4; + * @endcode + * This would cause a concept checking compile time error because the first value + * is an integer, not a double. Hence this would be passed to the templatised + * constructor and the concept check would fail. What was intended was that this + * be automatically casted before being sent to the assignment operator for the + * double. + * + * So here we generate a parent class and design the constructor in the Array + * to use that. We don't want to lose speed through virtual calls though, so we + * use the curiously recurring template pattern trick to get us to the goal! + * + * @sa @ref ecl::Array "Array". + */ +template +class ArrayBluePrint { + public: + /** + * A crtp virtual call to its children's instantiate method. The template + * argument is used, because the crtp base cannot catch typedef's in its + * children at this point of the compilation. With the template parameter + * this check is delayed until enough of this base class is known. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @return BaseType : the type to be generated by the blueprint. + */ + template + BaseType implementInstantiate() { + return static_cast(this)->instantiate(); + } + /** + * A crtp virtual call to its children's apply method. This acts on the + * blueprint's target class to configure it according to the blueprint. + * The template parameter is a trick to delay the determination of the + * target type, because at this point of the compilation it cannot + * retrieve the base_type from the derived type. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @param array : the underlying array to be configured. + */ + template + void implementApply(BaseType& array) const { + static_cast(this)->apply(array); + } + + virtual ~ArrayBluePrint() {} +}; +/** + * @brief Blueprint for instantiating/configuring an array filled with a constant. + * + * Implements the BluePrint concept for instantiating/configuring an array + * filled with a constant. + * + * @sa @ref ecl::Array "Array". + */ +template +class ConstantArray : public ArrayBluePrint< ConstantArray > { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::Array base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * This constructor saves the input parameters to use when generating the + * instance later. + * + * @param value : the constant value to fill the array with (defaults to zero). + */ + ConstantArray(const Type& value = 0) : val(value) {} + + virtual ~ConstantArray() {}; + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new array configured with a constant value. Take care + * not to use this in assignment, as it will do a costly copy of the entire + * array. It is, however, fine to use when constructing as the copy + * constructor will simply use this copy for the constructing object. + * + * @return Array : a copy of the array. + */ + base_type instantiate() { + ecl::Array array; + std::fill_n(array.begin(),Size,val); + return array; + } + + /** + * Fill all elements of an existing array with a constant value. + * @param array : the array to fill. + */ + void apply(base_type& array) const { + std::fill_n(array.begin(),Size,val); + } + + private: + const Type& val; +}; + +/** + * @brief BluePrint factory for the @ref ecl::Array "Array" class. + * + * Generates various blueprints that instantiate or configure arrays with + * commonly used configurations. + * + * @sa @ref ecl::Array "Array". + */ +template +class ArrayFactory { + public: + /** + * Generates a blueprint for creating constant arrays. The array constructor + * and assignment operator handle the usage of the blueprint from there. + * @param value : the value to fill the array with. + * @return ConstantArray : a blueprint for generating or configuring a constant array. + */ + static ConstantArray Constant(const Type& value) { + return ConstantArray(value); + } + + virtual ~ArrayFactory() {}; +}; + +} // namespace blueprints +} // namespace ecl + +#endif /* !ECL_MEM_CHECK_ARRAYS */ +#endif /* ECL_CONTAINERS_ARRAY_NO_MEM_CHECK_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/converters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/converters.hpp new file mode 100644 index 0000000..073c8d7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/converters.hpp @@ -0,0 +1,87 @@ +/** + * @file /ecl_containers/include/ecl/containers/converters.hpp + * + * @brief Some simple converters for ecl container types. + * + * @date August 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_CONVERTERS_HPP_ +#define ECL_CONTAINERS_ARRAY_CONVERTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#ifdef ECL_MEM_CHECK_ARRAYS + #include "array_mem_check.hpp" + #include "array_dynamic_mem_check.hpp" +#else + #include "array_no_mem_check.hpp" + #include "array_dynamic_no_mem_check.hpp" +#endif +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Byte Array Converters +*****************************************************************************/ + +/** + * @brief Specialisation for integral to char Array conversions. + * + * Note this will only work for dynamic containers as we can't possibly know the size + * of the container beforehand. + */ +template +class ECL_PUBLIC Converter , Integral > : public converters::IntegralToByteArray< Array, Integral > {}; + +/** + * @brief Specialisation for integral to signed char Array conversions. + * + * Note this will only work for dynamic containers as we can't possibly know the size + * of the container beforehand. + */ +template +class ECL_PUBLIC Converter , Integral > : public converters::IntegralToByteArray< Array, Integral > {}; + + +/** + * @brief Specialisation for integral to signed char Array conversions. + * + * Note this will only work for dynamic containers as we can't possibly know the size + * of the container beforehand. + */ +template +class ECL_PUBLIC Converter , Integral > : public converters::IntegralToByteArray< Array, Integral > {}; +/** + * @brief Specialisation for char Array container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray< Integral, Array > {}; + +/** + * @brief Specialisation for the unsigned char Array container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray< Integral, Array > {}; +/** + * @brief Specialisation for signed char Array container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray< Integral, Array > {}; + +} // namespace ecl + +#endif /* ECL_CONTAINERS_ARRAY_CONVERTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/formatters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/formatters.hpp new file mode 100644 index 0000000..ee12c52 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/array/formatters.hpp @@ -0,0 +1,327 @@ +/** + * @file /ecl_containers/include/ecl/containers/array/formatters.hpp + * + * @brief Text formatters for streaming array classes. + * + * @date September 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONTAINERS_ARRAY_FORMATTERS_HPP_ +#define ECL_CONTAINERS_ARRAY_FORMATTERS_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../common/formatters.hpp" +#include "../array.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ +namespace formatters +{ + +/***************************************************************************** + ** Using + *****************************************************************************/ + +/** + * @brief Pseudo formatter for integral type arrays. + * + * These do nothing but pass the array back for streaming. Do not use this + * class directly, rather call it via either the Array or Format classes + * explicitly. This makes the code more readable. e.g. + * + * @code + * // fixed array + * Array::Formatter format_array_1; + * Format< Array > format_array_2; // same thing + * + * // dynamic array + * Array::Formatter float_array_dynamic_formatter_1; + * Format< Array > format_array_dynamic_formatter_2; + * @endcode + * + * @tparam Type : the value type of the fixed size Array. + * @tparam N : the size of the container to be formatted. + * + * @todo Specialise the formatting for these integral type arrays so that they return + * formatting possibilities equivalent to their base type. + */ +template +class ECL_PUBLIC ArrayFormatter +{ +public: + virtual ~ArrayFormatter() + {} + /** + * Pseudo formatter method, simply returns the underlying array which + * has its own stream operator. + * @param array : the array to be formatted. + * @return Array : just returns the input array. + */ + ecl::Array& operator()(ecl::Array &array) { + return array; + } +}; + +/***************************************************************************** + ** Interface [ByteArrayFormatter] + *****************************************************************************/ + +/** + * @brief Parent template for the byte array formatters. + * + * We dont accept arguments for this class, it is simply + * designed to present byte arrays in hex format byte by byte. If you + * want specialised formatting for the character array, iterate over it + * with the Format (or signed/unsigned char) class. + * + * It will also accept stencils which have an underlying array of the + * required type. + * + * Do not use this class directly, rather call it via either the + * Array or Format classes explicitly. This makes the code more readable. e.g. + * + * @code + * Array::Formatter format_array_1; + * Format< Array > format_array_2; // same thing + * @endcode + * + * @tparam Byte : byte type, signed char/char/unsigned char. + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC ByteArrayFormatter +{ +public: + /** + * Default constructor that simply sets up the formatter for use. There + * is only one formatting style for this - a byte by byte view of the + * array in hex format, so we don't accept any arguments. If you want + * specialised formatting for your array, iterate it element by element + * with the Format class. + **/ + ByteArrayFormatter() : ready_to_format(false) + {}; + /** + * The format operator. Use this when inserting into a stream. It + * returns a template on which the stream will perform the formatting + * to create the requested output. + * @param array : the array to format. + * @return Format>& : this formatter readied for use by a stream. + */ + ByteArrayFormatter& operator()(const Array &array) + { + begin_iterator = array.begin(); + end_iterator = array.end(); + ready_to_format = true; + return *this; + } + /** + * The format operator. Use this when inserting into a stream. It + * returns a template on which the stream will perform the formatting + * to create the requested output. + * @param stencil : a stencil on an underlying array of the requisite type. + * @return Format< Array>& : this formatter readied for use by a stream. + */ + ByteArrayFormatter& operator()(const Stencil< Array > &stencil) + { + begin_iterator = stencil.begin(); + end_iterator = stencil.end(); + ready_to_format = true; + return *this; + } + /** + * @brief Formats on a window of the array. + * + * Format over the window specified. + * + * @param begin_iter : point in the array to begin formatting from. + * @param end_iter : point in the array to begin formatting to. + * @return Format>& : this formatter readied for use by a stream. + * + * @exception StandardException : throws if indices are out of range [debug mode only]. + */ + ByteArrayFormatter& operator()(typename Array::const_iterator begin_iter, + typename Array::const_iterator end_iter + ) + { + + begin_iterator = begin_iter; + end_iterator = end_iter; + ready_to_format = true; + return *this; + } + + virtual ~ByteArrayFormatter() + {} + /** + * Insertion operator for sending the formatter (for character arrays) to an output stream. + * @tparam OutputStream : the type of the output stream to be inserted into. + * @tparam M : the size of the container to be formatted. + * @param ostream : the output stream. + * @param formatter : the formatter to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + * + * @exception StandardException : throws if the formatter is used multiply in one stream operation [debug mode only]. + */ + template + friend OutputStream& operator << (OutputStream& ostream, const ByteArrayFormatter &formatter); + +private: + typename Array::const_iterator begin_iterator; + typename Array::const_iterator end_iterator; + bool ready_to_format; +}; + +/***************************************************************************** + ** Implementation [ByteArrayFormatter] + *****************************************************************************/ + +template +OutputStream& operator <<(OutputStream& ostream, const ByteArrayFormatter &formatter) +{ + ecl_assert_throw(formatter.ready_to_format, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + ecl::Format format(-1, ecl::NoAlign, ecl::Hex); + typename ecl::Array::const_iterator iter; +ostream << "[ "; + for ( iter = formatter.begin_iterator; iter != formatter.end_iterator; ++iter ) + { + ostream << format(*iter) << " "; + } + ostream << "]"; + ostream.flush(); + return ostream; +} + +/***************************************************************************** + ** Specialisations [ArrayFormatter][Char Types] + *****************************************************************************/ +/** + * @brief Convenience formatter for viewing a signed char array in hex format. + * + * We dont accept a wide range of arguments for this class, it is simply + * designed to present byte arrays in hex format byte by byte. If you + * want specialised formatting for the byte array, iterate over it + * with the Format (or signed/unsigned char) class. + * + * It will also accept stencils which have an underlying array of the + * required type. + * + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC ArrayFormatter< signed char,N > : public ByteArrayFormatter +{}; + +/** + * @brief Convenience formatter for viewing a char array in hex format. + * + * We dont accept a wide range of arguments for this class, it is simply + * designed to present byte arrays in hex format byte by byte. If you + * want specialised formatting for the byte array, iterate over it + * with the Format (or signed/unsigned char) class. + * + * It will also accept stencils which have an underlying array of the + * required type. + * + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC ArrayFormatter< char,N > : public ByteArrayFormatter +{}; + +/** + * @brief Convenience formatter for viewing an unsigned char array in hex format. + * + * We dont accept a wide range of arguments for this class, it is simply + * designed to present byte arrays in hex format byte by byte. If you + * want specialised formatting for the byte array, iterate over it + * with the Format (or signed/unsigned char) class. + * + * It will also accept stencils which have an underlying array of the + * required type. + * + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC ArrayFormatter< unsigned char,N > : public ByteArrayFormatter +{ +}; + +/** + * @brief Formatter for fixed size float arrays. + * + * Allows precision settings for formatting of fixed size float arrays. + * + * @tparam N : the size of the fixed size float array to be formatted. + * + * @sa @ref ecl::formatters::FloatContainerFormatter "FloatContainerFormatter". + */ +template +class ECL_PUBLIC ArrayFormatter< float,N > : public FloatContainerFormatter< Array > +{ +public: + /** + * @brief Default constructor. + * + * Optionally accepts a precision setting for the contents of the array. + * + * @param p : the number of decimal places of precision [default : 2]. + * @param w : width [default : no width constraint] + */ + ArrayFormatter(const int p=2, const int w=-1) : FloatContainerFormatter< Array >(p,w) + {}; + virtual ~ArrayFormatter() + {} +}; + +/** + * @brief Formatter for fixed size double arrays. + * + * Allows precision settings for formatting of fixed size double arrays. + * + * @tparam N : the size of the fixed size double array to be formatted. + * + * @sa @ref ecl::formatters::FloatContainerFormatter "FloatContainerFormatter". + */ +template +class ECL_PUBLIC ArrayFormatter< double,N > : public FloatContainerFormatter< Array > +{ +public: + /** + * @brief Default constructor. + * + * Optionally accepts a precision setting for the contents of the array. + * + * @param p : the number of decimal places of precision [default : 2]. + * @param w : width [default : no width constraint] + */ + ArrayFormatter(const int p=2, const int w=-1) : FloatContainerFormatter< Array >(p,w) + {}; + virtual ~ArrayFormatter() + {} +}; + +} // namespace formatters +} // namespace ecl + +#endif /* ECL_CONTAINERS_ARRAY_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/CMakeLists.txt new file mode 100644 index 0000000..cec5aa1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/containers/common) diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/formatters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/formatters.hpp new file mode 100644 index 0000000..9f07252 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/common/formatters.hpp @@ -0,0 +1,274 @@ +/** + * @file /ecl_containers/include/ecl/containers/array/formatters.hpp + * + * @brief Text formatters for streaming array classes. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_COMMON_FORMATTERS_HPP_ +#define ECL_CONTAINERS_COMMON_FORMATTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace formatters { + +/***************************************************************************** +** Using +*****************************************************************************/ + +/***************************************************************************** +** Interface [FloatContainerFormatter] +*****************************************************************************/ + +/** + * @brief Parent interface for formatters of fixed size float/double containers. + * + * This defines the common interface to be shared by fixed size float/double + * containers. It only allows configuration of width and precision to be used to + * format the elements of the container. Note that if the width is set to -1 (the default), + * this class automatically + * configures an appropriate width by scanning the elements within and setting it to the minimum + * width necessary to display all elements properly. + * + * Do not use this class directly, rather call it via either the + * Container type or Format classes explicitly. This makes the code more readable. e.g. + * + * @code + * Array::Formatter format_array_1; + * Format< Array > format_array_2; // same thing + * @endcode + * + * @tparam Container : the underlying fixed size float or double array. + * + * @sa ecl::formatters::Format< Array, ecl::formatters::Format>. + * + * Note, the above don't link properly to the partial specialisations. Look for them + * in the ecl::formatters namespace. + * + */ +template +class ECL_LOCAL FloatContainerFormatter { + public: + /****************************************** + ** Typedefs + *******************************************/ + typedef typename Container::value_type value_type; /**< @brief Catches the container element's type. **/ + + /** + * Constructor - can be used to define the precision required for the formatter's elements. + * + * @param p : the number of decimal places of precision [default : 2]. + * @param w : width [default : no width constraint] + **/ + FloatContainerFormatter(const unsigned int p = 2, const int w=-1) : + old_precision(-1), + tmp_width(-1), + prm_width(w), + width_ptr(&prm_width), + format(w,p,ecl::RightAlign,ecl::Fixed), + container(NULL), + ready_to_format(false) + {} + + virtual ~FloatContainerFormatter() {} + + /** + * @brief Sets the precision format parameter. + * + * Use this to set the precision of the displayed output. + * + * @param p : the number of decimal places of precision. + * @return FloatContainerFormatter& : this formatter readied for use with a stream. + **/ + FloatContainerFormatter& precision(const unsigned int p) { format.precision(p); return *this; } // Permanent + /** + * @brief Sets the width format parameter. + * + * Use this to configure the width of the displayed output. The formatter can be + * instructed to automatically determine a width suitable for all elements by setting + * this value to -1. + * + * @param w : the width to use for the inserted float [-1 for automatic resizing of cells]. + * @return FloatContainerFormatter& : this formatter readied for use with a stream. + **/ + FloatContainerFormatter& width(const int w) { prm_width = w; return *this; } // Permanent + /** + * @brief Access the current precision used by this formatter. + * + * Returns the current precision setting. + * @return int : the number of decimal places of precision. + */ + unsigned int precision() const { return format.precision(); } + /** + * Permanently sets the stream's precision format. This is simply a convenient + * version of the precision(p) method. + * @param p : the number of decimal places of precision. + * @param w : the width to use for the inserted float. + * @return FloatContainerFormatter& : this formatter readied for use with a stream. + */ + FloatContainerFormatter& operator()(const unsigned int p, const int w) { format.precision(p); prm_width = w; return *this; } // Permanent + /** + * Convenient stream formatter. This function directly readies the formatter + * with the specified container and the stored (permanent) settings. + * @code + * Format< Array > format; + * cout << format(array) << endl; + * @endcode + * @param c : the input container to be formatted. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FloatContainerFormatter& operator()(const Container &c) { container = &c; ready_to_format = true; return *this; } + /** + * Convenient stream formatter. This function directly readies the formatter + * with the specified container and configures a temporary setting for + * the precision (one-shot). + * @code + * Format< Array > format; + * cout << format(array,2) << endl; + * @endcode + * @param c : the input container to be formatted. + * @param p : the number of decimal places of precision. + * @param w : the width to use for the inserted float. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FloatContainerFormatter& operator()(Container &c, const unsigned int p, const int w) { + container = &c; + ready_to_format = true; + old_precision = format.precision(); + format.precision(p); + tmp_width = w; + width_ptr = &tmp_width; + return *this; + } //temporary + + /** + * @brief Insertion operator for sending the formatter to an output stream. + * + * @param ostream : the output stream. + * @param formatter : the formatter to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + * + * @exception StandardException : throws if the formatter is used multiply in one stream operation [debug mode only]. + */ + template + friend OutputStream& operator << (OutputStream& ostream, FloatContainerFormatter< Container_ > &formatter); + + private: + long digits(value_type min_coeff, value_type max_coeff); + + int old_precision; + int tmp_width, prm_width; + int* width_ptr; + Format< value_type > format; + const Container *container; + bool ready_to_format; +}; + +/** + * Compute the integral width. This accepts the minimum and maximum values in the array + * from which a minimum width that provides a common width for every element in the array + * to be fully displayed is determined. + * @param min_coeff : the minimum value in the array. + * @param max_coeff : the maximum value in the array. + * @return long : the width to use for the integral part of the co-efficients. + */ +template +long FloatContainerFormatter::digits(value_type min_coeff, value_type max_coeff) { + long min_digits, max_digits; + long actual_digits; + min_digits = static_cast ( ceil(log10(fabs(min_coeff)+1)) ); + max_digits = static_cast ( ceil(log10(fabs(max_coeff)+1)) ); + if ( min_digits < max_digits ) { + actual_digits = max_digits; + } else { + if ( ( min_digits == 0 ) && ( max_digits == 0 ) ) { + min_digits = 1; + } + actual_digits = min_digits; + } + if ( min_coeff < 0 ) { actual_digits += 1; } + actual_digits += 1 + format.precision(); + return actual_digits; +} + +/****************************************** +** Streamer +*******************************************/ + +template +OutputStream& operator << (OutputStream& ostream, FloatContainerFormatter< Container_ > &formatter) { + ecl_assert_throw(formatter.ready_to_format, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + if ( *(formatter.width_ptr) == -1 ) { + /****************************************** + ** Compute min,max coefficients + *******************************************/ + typename Container_::value_type min_coeff, max_coeff; + const typename Container_::value_type *cur_coeff; + min_coeff = (*formatter.container)[0]; + max_coeff = min_coeff; + +// for (size_t i = 1; i < N; ++i ) { + for ( unsigned int i = 1; i < formatter.container->size(); ++i) { + cur_coeff = &(*formatter.container)[i]; + if ( *cur_coeff > max_coeff ) { max_coeff = *cur_coeff; } + if ( *cur_coeff < min_coeff ) { min_coeff = *cur_coeff; } + } + /********************* + ** Set format width + **********************/ + formatter.format.width(formatter.digits(min_coeff,max_coeff)); + } else { + formatter.format.width(*(formatter.width_ptr)); + } + + /********************* + ** Stream + **********************/ + typename Container_::const_iterator iter; + ostream << "[ "; + for ( iter = formatter.container->begin(); iter != formatter.container->end(); ++iter ) { + ostream << formatter.format(*iter) << " "; + } + ostream << "]"; + + /********************* + ** Reset if temporary + **********************/ + if ( formatter.old_precision != -1 ) { + formatter.format.precision(formatter.old_precision); + formatter.old_precision = -1; + + } + formatter.width_ptr = &(formatter.prm_width); + formatter.ready_to_format = false; + + ostream.flush(); + return ostream; +} + +} // namespace formatters +} // namespace ecl + +#endif /* ECL_CONTAINERS_COMMON_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/converters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/converters.hpp new file mode 100644 index 0000000..fedf2d7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/converters.hpp @@ -0,0 +1,22 @@ +/** + * @file /include/ecl/containers/converters.hpp + * + * @brief Gathers the container converters. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_CONVERTERS_HPP_ +#define ECL_CONTAINERS_CONVERTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "array/converters.hpp" +#include "stencil/converters.hpp" + +#endif /* ECL_CONTAINERS_CONVERTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/definitions.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/definitions.hpp new file mode 100644 index 0000000..6e87d58 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/definitions.hpp @@ -0,0 +1,38 @@ +/** + * @file /include/ecl/containers/definitions.hpp + * + * @brief Some common container definitions. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_DEFINITIONS_HPP_ +#define ECL_CONTAINERS_DEFINITIONS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Enums +*****************************************************************************/ +/** + * @brief A simple flag for denoting the storage type of the container. + * + * This simply denotes whether the container is dynamic or fixed memory. + * Currently it is only used under the hood on the Array container. Users + * should not need to use this directly. + */ +enum StorageType { + DynamicStorage = 0,/**< Dynamic **/ + FixedStorage = 1 /**< Fixed **/ +}; + +} // namespace ecl + +#endif /* ECL_CONTAINERS_DEFINITIONS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/fifo.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/fifo.hpp new file mode 100644 index 0000000..2dddcc8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/fifo.hpp @@ -0,0 +1,181 @@ +/** + * @file /include/ecl/containers/fifo.hpp + * + * @brief A simple fifo implementation. + * + * Internally it uses ecl::Array for various error handling and other + * routines. + * + * @date August 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_FIFO_HPP_ +#define ECL_CONTAINERS_FIFO_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // std::copy +#include +#include +#include +#include "array.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface +*****************************************************************************/ +/** + * @brief Really simple fifo implementation. + * + * For control programs, fifo is typically used for data storage, + * moving average and some applications. It uses ecl::Array internally for + * storage (all exception handling is thus handled by ecl::Array). + * + * Usage: + * + * During the construction of fifo, typically length of buffer may be important. + * + * @code + * FiFo fifo(4); + * fifo.push_back( data_incoming ); + * + * But initial value for whole buffer can be important to you. + * Especially if you want to use fifo for moving average, + * you should wait for N (length of buffer) incoming of data. + * But if you use below code, you can use fifo immediately + * + * @code + * FiFo fifo(4, initial_value); // construct with initial value for whole buffer + * fifo.push_back( next_data ); // set next data + * ... // calculate the average here + * @endcode + * + * Data access + * + * [0] always return oldest data set from the fifo and [N-1] + * returns always new data from the fifo once your buffer is full. + * + * @code + * FiFo fifo(4); + * fifo.push_back(1.0); + * fifo.push_back(2.0); + * fifo.push_back(3.0); + * fifo.push_back(4.0); + * + * std::cout << fifo[0] << std::endl; // 1.0 + * std::cout << fifo[3] << std::endl; // 4.0 + * @endcode + * + * @sa ecl::Array. + */ +template +class ECL_PUBLIC FiFo +{ +public: + /** + * @brief Initialises the fifo, but does not fill it. + * @param length : size of the fifo. + */ + FiFo( const unsigned int length = 0 ) : + size_fifo(length), + running_index(0) + { + if ( size_fifo > 0 ) { + data.resize( size_fifo ); + } + } + + /** + * @brief Initialise and fill the fifo. + * @param length : the size of the fifo. + * @param value : the constant to fill the fifo with. + */ + FiFo( const unsigned int length, const T &value ) : + size_fifo(length), + running_index(0) + { + if ( size_fifo > 0 ) { + data = Array::Constant(size_fifo,value); + } + } + virtual ~FiFo() {} /**< @brief Default destructor. **/ + + /** + * @brief Returns the indexed value offset from the oldest data. + * + * This ensures that [0] returns always oldest data from the buffer, + * others will be offset from this. + * + * @param idx : index + * @return T& : reference (modifiable) to the indexed element. + */ + T & operator[] (int idx) { + return data[ ((running_index+idx)%size_fifo) ]; + } + + /** + * @brief Const version of the [] accessor. + * + * @param idx : index + * @return const T& : const reference to the indexed element. + */ + const T & operator[] (int idx) const { + return data[ ((running_index+idx)%size_fifo) ]; + } + + /** + * @brief Push back onto the fifo. + * + * This will overwrite the oldest element in the fifo. + * + * @param datum : incoming value. + */ + void push_back( const T & datum ) { + data[ running_index++ ] = datum; + running_index %= size_fifo; + } + + /** + * @brief One-shot fill method. + * @param value : the constant value to fill with. + */ + void fill( const T & value ) { + for( unsigned int i=0; i0), StandardException(LOC, OutOfRangeError, "SimpleFIFO start with zero size buffer")); + data.resize( size_fifo ); + } + +private: + ecl::Array data; + unsigned int size_fifo; + unsigned int running_index; +}; + +} // namespace ecl + +#endif /* ECL_CONTAINERS_FIFO_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/initialiser.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/initialiser.hpp new file mode 100644 index 0000000..999f443 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/initialiser.hpp @@ -0,0 +1,177 @@ +/** + * @file /include/ecl/containers/initialiser.hpp + * + * @brief Comma initialiser for container types. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_INITIALISER_HPP_ +#define ECL_CONTAINERS_INITIALISER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // size_t +#include "definitions.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace containers { + +/***************************************************************************** +** Interface [BoundedListInitialiser] +*****************************************************************************/ +/** + * @brief Convenience initialiser with bounds checking for fixed size containers. + * + * Initialises containers in a manner similar to that used in Blitz++ and Eigen2 + * with a comma separated list. It also does range checking in debug mode. + * The containers are assumed to have fixed storage length specified by the + * third template parameter. + * + * Error Handling + * + * Out of range operations will always throw an exception in debug mode. + * + * @sa Array, DynamicArray. + **/ +template +class ECL_LOCAL BoundedListInitialiser { + + public: + /** + * Gets a handle to an iterator of the underlying container and adds the first value. + * + * @param value : first element to be added to the initialiser. + * @param iter : a pointer to the current element to be added to the container. + */ + BoundedListInitialiser(const Type &value, Iterator iter); + + virtual ~BoundedListInitialiser() {} + + /** + * Convenience operator for initialising container types with a comma + * separated list. It uses a current BoundedListInitialiser instance to add the next value + * to the underlying class and returns the same instance with incremented iterator. + * + * @param value : the value to be inserted at the location of the stored iterator. + * @return BoundedListInitialiser : the initialiser class. + * + * @exception StandardException : throws if the range has been exceeded [debug mode only]. + */ + BoundedListInitialiser& operator,(const Type &value); + + protected: + Iterator iterator; + std::size_t current_size; +}; + +/***************************************************************************** +** Implementation [BoundedListInitialiser] +*****************************************************************************/ + +template +BoundedListInitialiser::BoundedListInitialiser(const Type &value, Iterator iter) : + iterator(iter), + current_size(1) +{ + *iterator = value; + ++iterator; +} +template +BoundedListInitialiser& BoundedListInitialiser::operator,(const Type &value) +{ + ecl_assert_throw( current_size < N, StandardException(LOC,OutOfRangeError) ); + *iterator = value; + iterator++; + current_size++; + return *this; +} + +/***************************************************************************** +** Interface [BoundedListInitialiser][Dynamic] +*****************************************************************************/ +/** + * @brief Convenience initialiser with bounds checking for dynamic containers. + * + * Initialises containers in a manner similar to that used in Blitz++ and Eigen2 + * with a comma separated list. It also does range checking in debug mode. + * The containers are assumed to have dynamic storage length retrievable from + * the container class itself. + * + * This is a specialisation of the fixed container bounded list initialiser. + * + * @sa BoundedClassInitialiser + **/ +template +class ECL_LOCAL BoundedListInitialiser { + + public: + /** + * Gets a handle to an iterator of the underlying container and adds the first value. + * + * @param value : first element to be added to the initialiser. + * @param iter : a pointer to the current element to be added to the container. + * @param bound : size of the container it is initialising. + * + * @exception StandardException : throws if this container has no storage capacity [debug mode only]. + */ + BoundedListInitialiser(const Type &value, Iterator iter, std::size_t bound); + + virtual ~BoundedListInitialiser() {} + /** + * Convenience operator for initialising container types with a comma + * separated list. It uses a current BoundedListInitialiser instance to add the next value + * to the underlying class and returns the same instance with incremented iterator. + * + * @param value : the value to be inserted at the location of the stored iterator. + * @return BoundedListInitialiser : the initialiser class. + * + * @exception StandardException : throws if the range has been exceeded [debug mode only]. + */ + BoundedListInitialiser& operator,(const Type &value); + + protected: + Iterator iterator; + std::size_t current_size; + const std::size_t upper_bound; +}; + +/***************************************************************************** +** Implementation [BoundedListInitialiser] +*****************************************************************************/ + +template +BoundedListInitialiser::BoundedListInitialiser(const Type &value, Iterator iter, std::size_t bound) : + iterator(iter), + current_size(1), + upper_bound(bound) +{ + ecl_assert_throw( current_size <= upper_bound, StandardException(LOC,OutOfRangeError) ); + *iterator = value; + ++iterator; +} +template +BoundedListInitialiser& BoundedListInitialiser::operator,(const Type &value) +{ + ecl_assert_throw( current_size < upper_bound, StandardException(LOC,OutOfRangeError) ); + *iterator = value; + iterator++; + current_size++; + return *this; +} + +} // namespace containers +} // namespace ecl + +#endif /* ECL_CONTAINERS_INITIALISER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop.hpp new file mode 100644 index 0000000..66ebee7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/containers/push_and_pop.hpp + * + * @brief A simple push and pop container. + * + * Gathering headers. + * + * @date August 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_PUSH_AND_POP_HPP_ +#define ECL_CONTAINERS_PUSH_AND_POP_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "push_and_pop/push_and_pop_dynamic.hpp" +#include "push_and_pop/push_and_pop_fixed.hpp" + +// make sure the utility classes get included. +#include "push_and_pop/formatters.hpp" + +#endif /* ECL_CONTAINERS_PUSH_AND_POP_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/CMakeLists.txt new file mode 100644 index 0000000..08ffa32 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/containers/push_and_pop) diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/formatters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/formatters.hpp new file mode 100644 index 0000000..0796050 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/formatters.hpp @@ -0,0 +1,210 @@ +/** + * @file /ecl_containers/include/ecl/containers/push_and_pop/formatters.hpp + * + * @brief File comment + * + * File comment + * + * @date Jun 4, 2012 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_PUSH_AND_POP_FORMATTERS_HPP_ +#define ECL_CONTAINERS_PUSH_AND_POP_FORMATTERS_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../common/formatters.hpp" +#include "../push_and_pop.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ +namespace formatters +{ + +/***************************************************************************** + ** Using + *****************************************************************************/ + +/** + * @brief Pseudo formatter for integral type arrays. + * + * These do nothing but pass the array back for streaming. Do not use this + * class directly, rather call it via either the Array or Format classes + * explicitly. This makes the code more readable. e.g. + * + * @code + * // fixed array + * PushAndPop::Formatter format_1; + * Format< PushAndPop > format_2; // same thing + * + * // dynamic array + * PushAndPop::Formatter float_dynamic_formatter_1; + * Format< PushAndPop > format_dynamic_formatter_2; + * @endcode + * + * @tparam Type : the value type of the fixed size Array. + * @tparam N : the size of the container to be formatted. + * + * @todo Specialise the formatting for these integral type arrays so that they return + * formatting possibilities equivalent to their base type. + */ +template +class ECL_PUBLIC PushAndPopFormatter +{ +public: + virtual ~PushAndPopFormatter() + {} + /** + * Pseudo formatter method, simply returns the underlying array which + * has its own stream operator. + * @param array : the array to be formatted. + * @return PushAndPop : just returns the input array. + */ + ecl::PushAndPop& operator()(const ecl::PushAndPop &container) { + return container; + } +}; + +/***************************************************************************** + ** Interface [ByteArrayFormatter] + *****************************************************************************/ + +/** + * @brief Parent template for the byte push and pop formatters. + * + * We dont accept arguments for this class, it is simply + * designed to present byte arrays in hex format byte by byte. If you + * want specialised formatting, iterate over it + * with the Format (or signed/unsigned char) class. + * + * Do not use this class directly, rather call it via either the + * PushAndPop or Format classes explicitly. This makes the code more readable. e.g. + * + * @code + * PushAndPop::Formatter format_array_1; + * Format< PushAndPop > format_array_2; // same thing + * @endcode + * + * @tparam Byte : byte type, signed char/char/unsigned char. + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC BytePushAndPopFormatter +{ +public: + /** + * Default constructor that simply sets up the formatter for use. There + * is only one formatting style for this - a byte by byte view of the + * array in hex format, so we don't accept any arguments. If you want + * specialised formatting for your array, iterate it element by element + * with the Format class. + **/ + BytePushAndPopFormatter() : ready_to_format(false) + {}; + /** + * The format operator. Use this when inserting into a stream. It + * returns a template on which the stream will perform the formatting + * to create the requested output. + * @param array : the array to format. + * @return Format>& : this formatter readied for use by a stream. + */ + BytePushAndPopFormatter& operator()(const ecl::PushAndPop &push_and_pop) + { + push_and_pop_container = &push_and_pop; + ready_to_format = true; + return *this; + } + + virtual ~BytePushAndPopFormatter() + {} + /** + * Insertion operator for sending the formatter (for character arrays) to an output stream. + * @tparam OutputStream : the type of the output stream to be inserted into. + * @tparam M : the size of the container to be formatted. + * @param ostream : the output stream. + * @param formatter : the formatter to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + * + * @exception StandardException : throws if the formatter is used multiply in one stream operation [debug mode only]. + */ + template + friend OutputStream& operator << (OutputStream& ostream, const BytePushAndPopFormatter &formatter); + +private: + const typename ecl::PushAndPop *push_and_pop_container; + bool ready_to_format; +}; + +/***************************************************************************** + ** Implementation [ByteArrayFormatter] + *****************************************************************************/ + +template +OutputStream& operator <<(OutputStream& ostream, const BytePushAndPopFormatter &formatter) +{ + ecl_assert_throw(formatter.ready_to_format, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + ecl::Format format(-1, ecl::NoAlign, ecl::Hex); + ostream << "[ "; + for ( unsigned int i = 0; i < formatter.push_and_pop_container->size(); ++i ) { + ostream << format((*(formatter.push_and_pop_container))[i]) << " "; + } + ostream << "]"; + ostream.flush(); + return ostream; +} + +/***************************************************************************** + ** Specialisations [PushAndPopFormatter][Char Types] + *****************************************************************************/ + +/** + * @brief Convenience formatter for viewing an unsigned char push and pop containers in hex format. + * + * We dont accept a wide range of arguments for this class, it is simply + * designed to present byte push and pop containers in hex format byte by byte. If you + * want specialised formatting for the byte array, iterate over it + * with the Format class. + * + * @tparam N : the size of the container to be formatted. + */ +template +class ECL_PUBLIC PushAndPopFormatter< unsigned char,N > +{ +public: + typename ecl::formatters::BytePushAndPopFormatter& operator()(const ecl::PushAndPop &container) { + return formatter(container); + } + +private: + typename ecl::formatters::BytePushAndPopFormatter formatter; +}; + + +/***************************************************************************** +** Not Yet Implemented - formatters for signed, char types +*****************************************************************************/ + +} // namespace formatters +} // namespace ecl + + +#endif /* ECL_CONTAINERS_PUSH_AND_POP_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_dynamic.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_dynamic.hpp new file mode 100644 index 0000000..22883b8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_dynamic.hpp @@ -0,0 +1,290 @@ +/** + * @file /include/ecl/containers/push_and_pop/push_and_pop_dynamic.hpp + * + * @brief A simple fifo implementation. + * + * Internally it uses ecl::Array for various error handling and other + * routines. + * + * @date August 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONTAINERS_PUSH_AND_POP_DYNAMIC_HPP_ +#define ECL_CONTAINERS_PUSH_AND_POP_DYNAMIC_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include "push_and_pop_fixed.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +namespace formatters { + +template class PushAndPopFormatter; + +} // namespace formatters + +/***************************************************************************** + ** Interface + *****************************************************************************/ +/** + * @brief + * Surpport push and pack operation + * + * ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! + * + * This is very experimental and has a few unfinished, surprising. + * automatic behaviours. + * + * - begin() and end() do not point to the beginning/end of the pushpop, + * rather they point to the beginning and ending of the underlying array + * - if full and pushing back, it makes room by popping off the front + * + * Usage: + * + * @code + * + * + * @code + * + * + * @endcode + * + * @sa ecl::Array. + */ +template +class ECL_PUBLIC PushAndPop +{ +public: + typedef Type value_type; /**< Element type. **/ + typedef Type* iterator; /**< Iterator type. **/ + typedef const Type* const_iterator; /**< Constant iterator type. **/ + typedef Type& reference; /**< Element reference type. **/ + typedef const Type& const_reference; /**< Element const reference type. **/ + typedef std::size_t size_type; /**< Type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< Reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< Constant reverse iterator type. **/ + typedef formatters::PushAndPopFormatter Formatter; /**< @brief Formatter for this class. **/ + + /** + * @brief Default constructor. + * + * Creates a dynamic push and pop container of zero length. + */ + PushAndPop() : size_fifo(0), leader(0), follower(0) {} + + PushAndPop( const unsigned int length ) + : size_fifo(length+1), leader(0), follower(0) + { + ecl_assert_throw( (size_fifo>0), StandardException(LOC, OutOfRangeError, "SimpleFIFO start with zero size buffer")); + data.resize( size_fifo ); + } + + PushAndPop( const unsigned int length, const Type & d ) : + size_fifo(length+1), + leader(0), + follower(0) + { + ecl_assert_throw( (size_fifo>0), StandardException(LOC, OutOfRangeError, "SimpleFIFO start with zero size buffer")); + data.resize( size_fifo ); + fill( d ); + } + virtual ~PushAndPop() + {} + + /********************* + ** Iterators + **********************/ + /* ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! */ + /* + * These have not been updated to take care with the push/pop, they just point to the + * start and end of the underlying array! + */ + /** + * Generates a pointer (iterator) pointing to the start of the array. + * @return iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator begin() { + return data.begin(); // underlying array will throw if no storage has been allocated + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator begin() const { + return data.begin(); // underlying array will throw if no storage has been allocated + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + iterator end() { + return data.end(); // underlying array will throw if no storage has been allocated + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_iterator end() const { + return data.end(); // underlying array will throw if no storage has been allocated + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rbegin() { + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + reverse_iterator rend() { + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * + * @exception StandardException : throws if no storage has been allocated [debug mode only]. + */ + const_reverse_iterator rend() const { + return const_reverse_iterator(begin()); + } + + + /********************* + ** Accessors + **********************/ + // Cannot do stencils easily as push and pop roll over - not guaranteed of being contiguous + + Type & operator[] (int idx) + { + return data[ ((follower+idx)%size_fifo) ]; + } + + const Type & operator[] (int idx) const + { + return data[ ((follower+idx)%size_fifo) ]; + } + + void operator() (const PushAndPop & otherOne ) + { + leader = otherOne.leader; + follower = otherOne.follower; + for( int i=0; i0), StandardException(LOC, OutOfRangeError, "SimpleFIFO start with zero size buffer")); + data.resize( size_fifo ); + } + + /** + * @brief The size allocated in memory for the fifo. + * + * This is different to the actual used size. + * + * @sa size() + */ + unsigned int asize() + { + return size_fifo; + } + + unsigned int size() const + { + if( leader > follower ) return leader - follower; + else if( leader < follower ) return size_fifo-follower+leader; + return 0; + } + + void clear() + { + follower = 0; + leader = 0; + } + +//protected: + ecl::Array data; + unsigned int size_fifo; + int leader; + int follower; +}; + +} // namespace ecl + +#endif /* ECL_CONTAINERS_PUSH_AND_POP_DYNAMIC_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_fixed.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_fixed.hpp new file mode 100644 index 0000000..cd5ef24 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/push_and_pop/push_and_pop_fixed.hpp @@ -0,0 +1,189 @@ +/** + * @file /include/ecl/containers/push_and_pop/push_and_pop_fixed.hpp + * + * @brief A simple fifo implementation. + * + * Internally it uses ecl::Array for various error handling and other + * routines. + * + * @date August 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONTAINERS_PUSH_AND_POP_FIXED_HPP_ +#define ECL_CONTAINERS_PUSH_AND_POP_FIXED_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include //showMe +#include // std::copy +#include +#include +#include +#include "../array.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +namespace formatters { + +template class PushAndPopFormatter; + +} // namespace formatters + +/***************************************************************************** + ** Interface + *****************************************************************************/ +/** + * @brief + * Surpport push and pack operation + * + * ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! ACHTUNG! + * + * This is very experimental and has a few unfinished, surprising. + * automatic behaviours. + * + * - if full and pushing back, it makes room by popping off the front + * + * Usage: + * + * + * @code + * + * + * @code + * + * + * @endcode + * + * @sa ecl::Array. + */ + +template +class ECL_PUBLIC PushAndPop +{ +public: + typedef formatters::PushAndPopFormatter Formatter; /**< @brief Formatter for this class. **/ + + PushAndPop() + : + size_fifo(Size+1), + leader(0), + follower(0) + { + } + + PushAndPop( const Type & d ) + : + size_fifo(Size+1), + leader(0), + follower(0) + { + ecl_assert_throw( (size_fifo>0), StandardException(LOC, OutOfRangeError, "SimpleFIFO start with zero size buffer")); + fill( d ); + } + virtual ~PushAndPop() + {} + + Type & operator[] (int idx) + { + return data[ ((follower+idx)%size_fifo) ]; + } + + const Type & operator[] (int idx) const + { + return data[ ((follower+idx)%size_fifo) ]; + } + + void operator() (const PushAndPop & otherOne ) + { + leader = otherOne.leader; + follower = otherOne.follower; + for( int i=0; i follower ) return leader - follower; + else if( leader < follower ) return size_fifo-follower+leader; + return 0; + } + + void clear() + { + follower = 0; + leader = 0; + } + + void showMe() + { + std::cout << "[Size|Leader|Follower]: " << size_fifo << "|" << leader << "|" << follower << std::endl; + } + +private: + ecl::Array data; + unsigned int size_fifo; + int leader; + int follower; +}; + +} // namespace ecl + +#endif /* ECL_CONTAINERS_PUSH_AND_POP_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil.hpp new file mode 100644 index 0000000..6acf89b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/containers/stencil.hpp + * + * @brief Windows over ecl type containers. + * + * Provides a windowed snapshot over a portion of an ecl container. This + * simply gathers the stencil headers. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_STENCIL_HPP_ +#define ECL_CONTAINERS_STENCIL_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "stencil/stencil.hpp" +#include "stencil/specialisations.hpp" +#include "stencil/converters.hpp" +#include "stencil/formatters.hpp" + +#endif /* ECL_CONTAINERS_STENCIL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/CMakeLists.txt new file mode 100644 index 0000000..2c67de5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/containers/stencil) diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/converters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/converters.hpp new file mode 100644 index 0000000..4e415aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/converters.hpp @@ -0,0 +1,109 @@ +/** + * @file /include/ecl/containers/stencil/converters.hpp + * + * @brief Some simple converters for ecl stencils. + * + * @date August 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONTAINERS_STENCIL_CONVERTERS_HPP_ +#define ECL_CONTAINERS_STENCIL_CONVERTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "stencil.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forware Declarations +*****************************************************************************/ + +template class Array; + +/***************************************************************************** +** Interface [Array] +*****************************************************************************/ + +/** + * @brief Specialisation for integral to char Stencil conversions. + */ +template +class ECL_PUBLIC Converter < Stencil< Array >, Integral > : public converters::IntegralToByteArray< Stencil< Array >, Integral > {}; + +/** + * @brief Specialisation for integral to unsigned char Stencil conversions. + */ +template +class ECL_PUBLIC Converter < Stencil< Array >, Integral > : public converters::IntegralToByteArray< Stencil< Array >, Integral > {}; + +/** + * @brief Specialisation for integral to signed char Stencil conversions. + */ +template +class ECL_PUBLIC Converter < Stencil< Array >, Integral > : public converters::IntegralToByteArray< Stencil< Array >, Integral > {}; + +/** + * @brief Specialisation for char Stencil container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > > : public converters::FromByteArray< Integral, Stencil< Array > > {}; + +/** + * @brief Specialisation for unsigned char Stencil container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > > : public converters::FromByteArray< Integral, Stencil< Array > > {}; + +/** + * @brief Specialisation for signed char Stencil container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > > : public converters::FromByteArray< Integral, Stencil< Array > > {}; + +/** + * @brief Specialisation for unsigned int to vector based unsigned char Stencil container. + */ +template <> +class ECL_PUBLIC Converter< Stencil< std::vector >, unsigned int > : public converters::IntegralToByteArray< Stencil< std::vector >, unsigned int > {}; + +/** + * @brief Specialisation for int to vector based unsigned char Stencil container. + */ +template <> +class ECL_PUBLIC Converter< Stencil< std::vector >, int > : public converters::IntegralToByteArray< Stencil< std::vector >, int > {}; + +/** + * @brief Specialisation for long to vector based unsigned char Stencil container. + */ +template <> +class ECL_PUBLIC Converter< Stencil< std::vector >, long > : public converters::IntegralToByteArray< Stencil< std::vector >, long > {}; + +/** + * @brief Specialisation for long long to vector based unsigned char Stencil container. + */ +template <> +class ECL_PUBLIC Converter< Stencil< std::vector >, long long > : public converters::IntegralToByteArray< Stencil< std::vector >, long long > {}; + +/** + * @brief Specialisation for const unsigned char* Stencil container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray< Integral, Stencil< const unsigned char* > > {}; + + +} // namespace ecl + +#endif /* ECL_CONTAINERS_STENCIL_CONVERTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/formatters.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/formatters.hpp new file mode 100644 index 0000000..43e77e3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/formatters.hpp @@ -0,0 +1,122 @@ +/** + * @file /ecl_containers/include/ecl/containers/stencil/formatters.hpp + * + * @brief Text formatters for streaming stencil classes. + * + * @date March 11 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONTAINERS_STENCIL_FORMATTERS_HPP_ +#define ECL_CONTAINERS_STENCIL_FORMATTERS_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "../common/formatters.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Forward Declarations + *****************************************************************************/ + +template + class Stencil; + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace formatters +{ + +/***************************************************************************** + ** Using + *****************************************************************************/ + +/** + * @brief Pseudo formatter for stencils. + * + * These do nothing but pass the stencil back for streaming which should have + * its own << operator. + * + * Do not use this class directly, rather call it via either the Array or + * Format classes explicitly. This makes the code more readable. e.g. + * + * @code + * Stencil< Array >::Formatter format_1; + * Format< Stencil< Array > > format_2; // same thing + * @endcode + * + * @tparam ValueType : the underlying container's element type. + * @tparam Container : the underlying container storage. + * @tparam Enable : dummy template parameter used for mpl. + */ +template +class ECL_PUBLIC StencilFormatter +{ +public: + virtual ~StencilFormatter() + {} + /** + * Pseudo formatter method, simply returns the underlying stencil which + * has its own stream operator. + * @param stencil : the stencil to be formatted. + * @return Stencil< Container > : just returns the input array. + */ + const ecl::Stencil< Container >& operator()(const ecl::Stencil< Container > &stencil) { + return stencil; + } + //ecl::Stencil< Container >& operator()(const ecl::Stencil< Container > &stencil) { return stencil;} // this was the old version - couldn't do in place format(xxx.stencil()) commands +}; + +/***************************************************************************** + ** Specialisations + *****************************************************************************/ + +/** + * @brief Partial specialisation of the stencil formatter for float containers. + * + * Allows precision settings for formatting of float stencils. + * + * @tparam N : the size of the fixed size float array to be formatted. + * + * @sa @ref ecl::formatters::FloatContainerFormatter "FloatContainerFormatter". + */ +template +class ECL_PUBLIC StencilFormatter< ValueType, Container, typename ecl::enable_if< ecl::is_float >::type > : public FloatContainerFormatter< ecl::Stencil< Container > > +{ +public: + /** + * @brief Default constructor. + * + * Optionally accepts a precision setting for the contents of the array. + * + * @param p : the number of decimal places of precision [default : 2]. + * @param w : width [default : no width constraint] + */ + StencilFormatter(const int p=2, const int w=-1) : FloatContainerFormatter< ecl::Stencil< Container > >(p,w) {}; + virtual ~StencilFormatter() + {} +}; + +} // namespace formatters +} // namespace ecl + +#endif /* ECL_CONTAINERS_STENCIL_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/specialisations.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/specialisations.hpp new file mode 100644 index 0000000..8bcbdbd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/specialisations.hpp @@ -0,0 +1,833 @@ +/** + * @file /ecl_containers/include/ecl/containers/stencil/specialisations.hpp + * + * @brief Short description of this file. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_containers_SPECIALISATIONS_HPP_ +#define ecl_containers_SPECIALISATIONS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "stencil.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** + ** Interface + *****************************************************************************/ +/** + * @brief Stencil variant operating on a raw unsigned char array. + * + * This of course assumes the user is responsible for range checking on the + * unsigned char array. + * + * TODO : generalise this for T*. + * + * @sa ecl::Stencil + */ +template <> +class ECL_PUBLIC Stencil +{ +public: + /********************* + ** Typedefs + **********************/ + typedef unsigned char value_type; /**< @brief Uses the array's element type. **/ + typedef unsigned char* iterator; /**< @brief Uses the array's iterator type. **/ + typedef const unsigned char* const_iterator; /**< @brief Uses the array's constant iterator type. **/ + typedef unsigned char& reference; /**< @brief Uses the array's element reference type. **/ + typedef const unsigned char& const_reference; /**< @brief Uses the array's element const reference type. **/ + typedef std::size_t size_type; /**< @brief Uses the array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< @brief Uses the array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< @brief Uses the array's constant reverse iterator type. **/ + //typedef formatters::StencilFormatter Formatter; + + /********************* + ** C&D's + **********************/ + /** + * @brief Initialises with a pointer to the underlying array with boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * stl containers. + * + * @param underlying_array : reference to the underlying array. + * @param length : of the underlying array + * @param begin_iter : start of the stencil window. + * @param end_iter : end of the stencil window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(iterator underlying_array, const unsigned int& length, iterator begin_iter, iterator end_iter) : + array(underlying_array), + length(length), + b_iter(begin_iter), + e_iter(end_iter) + { + ecl_assert_throw((b_iter <= array+length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array+length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + /** + * @brief Initialises with a reference to the underlying array and boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * eigen block intialisations. + * + * @param underlying_array : reference to the underlying array. + * @param length : of the underlying array + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(iterator underlying_array, const unsigned int& length, const unsigned int& start_index = 0, const unsigned int &n = 0) : + array(underlying_array), + length(length), + b_iter(array+start_index), + e_iter(array+start_index+n) + { + ecl_assert_throw((b_iter <= array+length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array+length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + virtual ~Stencil() + {}; + + /** + * @brief Generate a sub-stencil. + * + * Opens another window on this stencil. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated sub-stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil stencil(const unsigned int& start_index, const unsigned int& n) const + { + ecl_assert_throw( b_iter+start_index <= array+length, StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying stencil size.")); + ecl_assert_throw( b_iter+start_index+n <= array+length, StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying stencil size.")); + // cant do out of range errors here (no idea how long the underlying array is!) + return Stencil(array,length,b_iter+start_index,b_iter+start_index+n); + } + + /** + * @brief Resettle the stencil on a different range over the same underlying array. + * + * Resets the range of the stencil operating on the currently referenced array. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + void resettle(const unsigned int& start_index, const unsigned int& n) + { + + b_iter = array+start_index; + e_iter = array+start_index+n; + ecl_assert_throw((b_iter <= array + length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array + length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * unsigned char buffer[4]; // At this point it is uninitialised. + * buffer << 0xff, 0x00, 0x01, 0x02; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<< (const value_type &value) + { + return containers::BoundedListInitialiser(value, begin(), size()); + } + /** + * @brief This either resettles this stencil or copies across to it (depending on the rhs stencil). + * + * The assignment operator has one of two effects - it will either + * reassign this stencil if both stencils work on the same underlying + * array, OR it copies across if acting on two different arrays. + * + * @param s + * @return Stencil : a handle to this stencil + * + * @exception : StandardException : if copying from another stencil/array, throws if size exceeded [debug mode only]. + * @see Stencil + */ + Stencil& operator=(const Stencil &s) + { + array = s.array; + length = s.length; + b_iter = s.b_iter; + e_iter = s.e_iter; + return *this; + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the stencil. + * @return iterator : points to the beginning of the stencil. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator begin() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator begin() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator end() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator end() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rbegin() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rbegin() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rend() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rend() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(begin()); + } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference front() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference front() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference back() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference back() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + + /********************* + ** Accessors + **********************/ + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) + { + ecl_assert_throw( b_iter+i >= array, StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array+length, StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @return const_reference : a constant reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + const_reference operator[](size_type i) const + { + ecl_assert_throw( b_iter+i >= array, StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array+length, StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. + * + * @param i : the index of the requested element. + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + reference at(size_type i) + { + if ( b_iter+i <= array ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array+length ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const + { + if ( b_iter+i <= array ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array+length ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + + /********************* + ** Utilities + **********************/ + /** + * The size of the stencil. + * + * @return size_type : the size of the stencil. + */ + size_type size() const + { return e_iter-b_iter;} + + /********************* + ** Streaming + **********************/ + /** + * @brief Insertion operator for stencils. + * + * Insertion operator for sending the stencil to an output stream. This + * is raw, and has no formatting. + * + * Concept Check: makes sure the template parameter provided for the stream + * is a stream type with the required functionality. + * + * @param ostream : the output stream. + * @param stencil : the stencil to be inserted. + * @tparam OutputStream : the stream being used. + * @tparam ArrayType : the type of the underlying array. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Stencil &stencil); + +private: + iterator array; + unsigned int length; + iterator b_iter, e_iter; +}; + +/***************************************************************************** + ** Const Specialisations + *****************************************************************************/ + +/** + * @brief Stencil variant operating on a raw const unsigned char array. + * + * This of course assumes the user is responsible for range checking on the + * unsigned char array. + * + * TODO : generalise this for const T*. + * + * @sa ecl::Stencil + */ +template <> +class ECL_PUBLIC Stencil +{ +public: + /********************* + ** Typedefs + **********************/ + typedef unsigned char value_type; /**< @brief Uses the array's element type. **/ + typedef const unsigned char* iterator; /**< @brief Uses the array's iterator type. **/ + typedef const unsigned char* const_iterator; /**< @brief Uses the array's constant iterator type. **/ + typedef const unsigned char& reference; /**< @brief Uses the array's element reference type. **/ + typedef const unsigned char& const_reference; /**< @brief Uses the array's element const reference type. **/ + typedef std::size_t size_type; /**< @brief Uses the array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< @brief Uses the array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< @brief Uses the array's constant reverse iterator type. **/ + //typedef formatters::StencilFormatter Formatter; + + /********************* + ** C&D's + **********************/ + /** + * @brief Initialises with a pointer to the underlying array with boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * stl containers. + * + * @param underlying_array : reference to the underlying array. + * @param length : of the underlying array + * @param begin_iter : start of the stencil window. + * @param end_iter : end of the stencil window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(const_iterator underlying_array, const unsigned int& length, const_iterator begin_iter, const_iterator end_iter) : + array(underlying_array), + length(length), + b_iter(begin_iter), + e_iter(end_iter) + { + ecl_assert_throw((b_iter <= array+length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array+length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + /** + * @brief Initialises with a reference to the underlying array and boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * eigen block intialisations. + * + * @param underlying_array : reference to the underlying array. + * @param length : of the underlying array + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(const_iterator underlying_array, const unsigned int& length, const unsigned int& start_index = 0, const unsigned int &n = 0) : + array(underlying_array), + length(length), + b_iter(array+start_index), + e_iter(array+start_index+n) + { + ecl_assert_throw((b_iter <= array+length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array+length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + virtual ~Stencil() + {}; + + /** + * @brief Generate a sub-stencil. + * + * Opens another window on this stencil. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated sub-stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil stencil(const unsigned int& start_index, const unsigned int& n) const + { + ecl_assert_throw( b_iter+start_index <= array+length, StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying stencil size.")); + ecl_assert_throw( b_iter+start_index+n <= array+length, StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying stencil size.")); + // cant do out of range errors here (no idea how long the underlying array is!) + return Stencil(array,length,b_iter+start_index,b_iter+start_index+n); + } + + /** + * @brief Resettle the stencil on a different range over the same underlying array. + * + * Resets the range of the stencil operating on the currently referenced array. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + void resettle(const unsigned int& start_index, const unsigned int& n) + { + + b_iter = array+start_index; + e_iter = array+start_index+n; + ecl_assert_throw((b_iter <= array + length), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter <= array + length), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + /** + * @brief This either resettles this stencil or copies across to it (depending on the rhs stencil). + * + * The assignment operator has one of two effects - it will either + * reassign this stencil if both stencils work on the same underlying + * array, OR it copies across if acting on two different arrays. + * + * @param s + * @return Stencil : a handle to this stencil + * + * @exception : StandardException : if copying from another stencil/array, throws if size exceeded [debug mode only]. + * @see Stencil + */ + Stencil& operator=(const Stencil &s) + { + array = s.array; + length = s.length; + b_iter = s.b_iter; + e_iter = s.e_iter; + return *this; + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the stencil. + * @return iterator : points to the beginning of the stencil. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator begin() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator begin() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator end() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator end() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rbegin() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rbegin() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rend() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rend() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(begin()); + } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference front() + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference front() const + { + ecl_assert_throw( b_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference back() + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference back() const + { + ecl_assert_throw( e_iter <= array+length, StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + + /********************* + ** Accessors + **********************/ + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) + { + ecl_assert_throw( b_iter+i >= array, StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array+length, StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @return const_reference : a constant reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + const_reference operator[](size_type i) const + { + ecl_assert_throw( b_iter+i >= array, StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array+length, StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. + * + * @param i : the index of the requested element. + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + reference at(size_type i) + { + if ( b_iter+i <= array ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array+length ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const + { + if ( b_iter+i <= array ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array+length ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + + /********************* + ** Utilities + **********************/ + /** + * The size of the stencil. + * + * @return size_type : the size of the stencil. + */ + size_type size() const + { return e_iter-b_iter;} + + /********************* + ** Streaming + **********************/ + /** + * @brief Insertion operator for stencils. + * + * Insertion operator for sending the stencil to an output stream. This + * is raw, and has no formatting. + * + * Concept Check: makes sure the template parameter provided for the stream + * is a stream type with the required functionality. + * + * @param ostream : the output stream. + * @param stencil : the stencil to be inserted. + * @tparam OutputStream : the stream being used. + * @tparam ArrayType : the type of the underlying array. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Stencil &stencil); + +private: + const_iterator array; + unsigned int length; + const_iterator b_iter, e_iter; +}; + +} // namespace ecl + +#endif /* ecl_containers_SPECIALISATIONS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/stencil.hpp b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/stencil.hpp new file mode 100644 index 0000000..c3f8d30 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/include/ecl/containers/stencil/stencil.hpp @@ -0,0 +1,528 @@ +/** + * @file /include/ecl/containers/stencil/stencil.hpp + * + * @brief Windows over ecl type containers. + * + * Provides a windowed snapshot over a portion of an ecl container. + * + * @date March 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONTAINERS_STENCIL_STENCIL_HPP_ +#define ECL_CONTAINERS_STENCIL_STENCIL_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include // size_t +#include +#include +#include +#include +#include "../initialiser.hpp" +#include "formatters.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Interface + *****************************************************************************/ +/** + * @brief A safe windowing class that opens onto array-like containers. + * + * Functions often require access to just a portion of an array. In these cases + * pointers are typically used, but these end up being dangerous alot of times. + * The underlying array may disappear, or its size may change and the resulting + * pointers are left dangling, pointing at rubbish. + * + * This class allows such an operation to be performed with two additional + * benefits: + * + * - It provides additional container like functionality. + * - Users references and range checking to ensure critical problems cannot arise. + * + * Currently this works with anything that measures up to the ecl concept of a + * container. + * + * Usage: + * + * @code + * typedef Array FixedArray; + * typedef Stencil< FixedArray > FixedStencil; + * + * FixedArray array; + * array << 1,2,3,4,5; + * FixedStencil stencil(array,1,3); // windows from index 1 to 3 + * std::cout << stencil[1] << std::endl; // accesses array[2]; + * + * @endcode + * + * @sa ecl::ContainerConcept, ecl::Array. + */ +template +class ECL_PUBLIC Stencil +{ +public: + /********************* + ** Typedefs + **********************/ + typedef typename Array::value_type value_type; /**< @brief Uses the array's element type. **/ + // Looks like I'm now needing to rely on the underlying storage iterator definitions + // Naturally, this means I can't do stencils of c arrays, but hey, thats dangerous anyway and we want to avoid that. + typedef typename Array::iterator iterator; /**< @brief Uses the array's iterator type. **/ + typedef typename Array::const_iterator const_iterator; /**< @brief Uses the array's constant iterator type. **/ + typedef typename Array::reference reference; /**< @brief Uses the array's element reference type. **/ + typedef typename Array::const_reference const_reference; /**< @brief Uses the array's element const reference type. **/ + // typedef typename Array::value_type* iterator; /**< @brief Uses the array's iterator type. **/ + // typedef const typename Array::value_type* const_iterator; /**< @brief Uses the array's constant iterator type. **/ + // typedef typename Array::value_type& reference; /**< @brief Uses the array's element reference type. **/ + // typedef const typename Array::value_type& const_reference; /**< @brief Uses the array's element const reference type. **/ + typedef std::size_t size_type; /**< @brief Uses the array's type used to denote the length of the array. **/ + typedef std::ptrdiff_t difference_type; + typedef std::reverse_iterator reverse_iterator; /**< @brief Uses the array's reverse iterator type. **/ + typedef std::reverse_iterator const_reverse_iterator; /**< @brief Uses the array's constant reverse iterator type. **/ + typedef formatters::StencilFormatter Formatter; + + /********************* + ** C&D's + **********************/ + /** + * @brief Initialises with a reference to the underlying container and boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * stl containers. + * + * Concept Check: makes sure the template parameter provided for the class is + * a container type with the required functionality. + * + * @param underlying_array : reference to the underlying array. + * @param begin_iter : start of the stencil window. + * @param end_iter : end of the stencil window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(Array& underlying_array, iterator begin_iter, iterator end_iter) : + array(underlying_array), + b_iter(begin_iter), + e_iter(end_iter) + { + ecl_compile_time_concept_check(ContainerConcept); + ecl_assert_throw((b_iter >= array.begin()) && (b_iter <= array.end()), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter >= array.begin()) && (e_iter <= array.end()), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + /** + * @brief Initialises with a reference to the underlying container and boundary constraints. + * + * Sets up the underlying storage container along with boundary constraints in the style of + * eigen block intialisations. + * + * Concept Check: makes sure the template parameter provided for the class is + * a container type with the required functionality. + * + * @param underlying_array : reference to the underlying array. + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil(Array& underlying_array, const unsigned int& start_index = 0, const unsigned int &n = 0) : + array(underlying_array), + b_iter(array.begin()+start_index), + e_iter(array.begin()+start_index+n) + { + ecl_compile_time_concept_check(ContainerConcept); + ecl_assert_throw((b_iter >= array.begin()) && (b_iter <= array.end()), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter >= array.begin()) && (e_iter <= array.end()), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + virtual ~Stencil() + {}; + + /** + * @brief Generate a sub-stencil. + * + * Opens another window on this stencil. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * @return Stencil : the generated sub-stencil. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + Stencil stencil(const unsigned int& start_index, const unsigned int& n) const + { + ecl_assert_throw( b_iter+start_index < array.end(), StandardException(LOC, OutOfRangeError, "Start index provided is larger than the underlying stencil size.")); + ecl_assert_throw( b_iter+start_index+n <= array.end(), StandardException(LOC, OutOfRangeError, "Finish index provided is larger than the underlying stencil size.")); + return Stencil(array,b_iter+start_index,b_iter+start_index+n); + } + + /** + * @brief Resettle the stencil on a different range over the same underlying array. + * + * Resets the range of the stencil operating on the currently referenced array. + * Using a starting index + size is in line with the way eigen blocks and segments work. + * + * @param start_index : start of the stencil window. + * @param n : number of elements to include in the window. + * + * @exception : StandardException : throws if the indices provided are out of range [debug mode only]. + */ + void resettle(const unsigned int& start_index, const unsigned int& n) + { + + b_iter = array.begin()+start_index; + e_iter = array.begin()+start_index+n; + ecl_assert_throw((b_iter >= array.begin()) && (b_iter <= array.end()), StandardException(LOC, OutOfRangeError, "Begin iterator out of range.")); + ecl_assert_throw((e_iter >= array.begin()) && (e_iter <= array.end()), StandardException(LOC, OutOfRangeError, "End iterator out of range.")); + } + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying array and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * Array array; // At this point it is uninitialised. + * array << 1,2,3,4; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first value to enter , ElementType, ArraySizeinto the array. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + containers::BoundedListInitialiser operator<< (const value_type &value) + { + return containers::BoundedListInitialiser(value, begin, size()); + } + /** + * @brief This either resettles this stencil or copies across to it (depending on the rhs stencil). + * + * The assignment operator has one of two effects - it will either + * reassign this stencil if both stencils work on the same underlying + * array, OR it copies across if acting on two different arrays. + * + * Usage: + * + * The first case, resettling: + * + * @code + * Array array(5); array << 1,2,3,4,5; + * Stencil< Array > stencil = array.stencil(1,2); + * stencil = array.stencil(0,3); // Here we can repeat the reassignment + * @endcode + * + * The second case, copying: + * @code + * Array array1(5); array1 << 1,2,3,4,5; + * Array array2(6); array2 << 1,2,3,4,5,6; + * Stencil< Array > stencil = array1.stencil(1,2); + * stencil = array2.stencil(2,2); // Here we just flood fill the stencil - make sure the capacity is sufficient! + * @endcode + * + * @param s + * @return Stencil : a handle to this stencil + * + * @exception : StandardException : if copying from another stencil/array, throws if size exceeded [debug mode only]. + */ + Stencil& operator=(const Stencil &s) + { + if ( &array == &(s.array) ) + { // resettle + b_iter = s.b_iter; + e_iter = s.e_iter; + } + else + { // copy + ecl_assert_throw( s.size() <= size(), StandardException(LOC, OutOfRangeError, "Stencil to be copied is larger than this stencil's size.")); + for ( unsigned int i = 0; i < s.size(); ++i ) + { + *(b_iter+i) = *(s.b_iter+i); + } + } + return *this; + } + + /********************* + ** Iterators + **********************/ + /** + * Generates a pointer (iterator) pointing to the start of the stencil. + * @return iterator : points to the beginning of the stencil. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator begin() + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates a const pointer (iterator) pointing to the start of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator begin() const + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return b_iter; + } + /** + * Generates an pointer (iterator) pointing to the end of the array. + * @return iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + iterator end() + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a const pointer (iterator) pointing to the end of the array. + * @return const_iterator : constant pointer (iterator) pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_iterator end() const + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return e_iter; + } + /** + * Generates a reverse iterator pointing to the end of the array. + * @return reverse_iterator : points to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rbegin() + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return reverse_iterator(end()); + } + /** + * Generates a constant reverse iterator pointing to the end of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the end of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rbegin() const + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(end()); + } + /** + * Generates a reverse iterator pointing to the beginning of the array. + * @return reverse_iterator : points to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reverse_iterator rend() + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return reverse_iterator(begin()); + } + /** + * Generates a constant reverse iterator pointing to the beginning of the array. + * @return const_reverse_iterator : constant reverse iterator pointing to the beginning of the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reverse_iterator rend() const + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return const_reverse_iterator(begin()); + } + + /********************* + ** Front/Back + **********************/ + /** + * Generates an reference to the first element in the array. + * @return reference : reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference front() + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates a constant reference to the first element in the array (cannot change the value). + * @return const_reference : const_reference to the first element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference front() const + { + ecl_assert_throw( b_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return *b_iter; + } + /** + * Generates an reference to the last element in the array. + * @return reference : reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + reference back() + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + /** + * Generates a constant reference to the last element in the array (cannot change the value). + * @return const_reference : const_reference to the last element in the array. + * @exception : StandardException : throws if the underlying array changed size and the stencil is now out of range [debug mode only]. + */ + const_reference back() const + { + ecl_assert_throw( e_iter <= array.end(), StandardException(LOC,OutOfRangeError)); + return *(e_iter-1); + } + + /********************* + ** Accessors + **********************/ + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. + * + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + reference operator[](size_type i) + { + ecl_assert_throw( b_iter+i >= array.begin(), StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array.end(), StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor only does range checks in debug mode (NDEBUG is not defined). Compare this with + * the at() accessor which always checks if the range is exceeded. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @return const_reference : a constant reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range [debug mode only]. + **/ + const_reference operator[](size_type i) const + { + ecl_assert_throw( b_iter+i >= array.begin(), StandardException(LOC,OutOfRangeError)); + ecl_assert_throw( b_iter+i <= array.end(), StandardException(LOC,OutOfRangeError)); + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. + * + * @param i : the index of the requested element. + * @return reference : a reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + reference at(size_type i) + { + if ( b_iter+i <= array.begin() ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array.end() ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + /** + * Accesses elements in the stencil, returning references to the requested element. This + * accessor always does range checks. Compare this with + * the [] accessor which only checks if NDEBUG is not defined. This also ensures the + * references are constant, which in turn ensures the contents cannot of the array cannot be + * modified. + * + * @param i : the index of the requested element. + * @return const_reference : a const_reference to the requested element. + * + * @exception : StandardException : throws if range is requested element is out of range. + */ + const_reference at(size_type i) const + { + if ( b_iter+i <= array.begin() ) + { + throw StandardException(LOC,OutOfRangeError); + } + if ( b_iter+i >= array.end() ) + { + throw StandardException(LOC,OutOfRangeError); + } + return *(b_iter+i); + } + + /********************* + ** Utilities + **********************/ + /** + * The size of the stencil. + * + * @return size_type : the size of the stencil. + */ + size_type size() const + { return e_iter-b_iter;} + + /********************* + ** Streaming + **********************/ + /** + * @brief Insertion operator for stencils. + * + * Insertion operator for sending the stencil to an output stream. This + * is raw, and has no formatting. + * + * Concept Check: makes sure the template parameter provided for the stream + * is a stream type with the required functionality. + * + * @param ostream : the output stream. + * @param stencil : the stencil to be inserted. + * @tparam OutputStream : the stream being used. + * @tparam ArrayType : the type of the underlying array. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Stencil &stencil); + +private: + Array& array; + iterator b_iter, e_iter; +}; + +/***************************************************************************** + ** Implementation [Streaming] + *****************************************************************************/ + +template + OutputStream& operator<<(OutputStream &ostream, const Stencil &stencil) + { + + ecl_compile_time_concept_check (StreamConcept ); + + ostream << "[ "; + for (std::size_t i = 0; i < stencil.size(); ++i) + { + ostream << stencil[i] << " "; + } + ostream << "]"; + ostream.flush(); + + return ostream; + } + +} // namespace ecl + +#endif /* ECL_CONTAINERS_STENCIL_STENCIL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_containers/package.xml b/ros2_ws/src/ecl_core/ecl_containers/package.xml new file mode 100644 index 0000000..a3533cf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/package.xml @@ -0,0 +1,52 @@ + + + ecl_containers + 1.2.1 + + The containers included here are intended to extend the stl containers. + In all cases, these implementations are designed to implement + c++ conveniences and safety where speed is not sacrificed. + + Also includes techniques for memory debugging of common problems such + as buffer overruns. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_containers + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_formatters + ecl_converters + ecl_mpl + ecl_type_traits + ecl_utilities + + ecl_license + ecl_config + ecl_errors + ecl_exceptions + ecl_formatters + ecl_converters + ecl_mpl + ecl_type_traits + ecl_utilities + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/src/CMakeLists.txt new file mode 100644 index 0000000..198acdd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(examples) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/src/examples/CMakeLists.txt new file mode 100644 index 0000000..027a311 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/examples/CMakeLists.txt @@ -0,0 +1,27 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_containers_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries( + ecl_demo_${name} + PUBLIC + ecl_config::ecl_config + ecl_converters::ecl_converters + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits + ecl_utilities::ecl_utilities + ) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_containers_add_demo(formatters) diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/examples/formatters.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/examples/formatters.cpp new file mode 100644 index 0000000..44eaeaa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/examples/formatters.cpp @@ -0,0 +1,188 @@ +/** + * @file /ecl_containers/src/examples/array_formatters.cpp + * + * @brief Example (and coverage) for the array formatters. + * + * Can't easily do tests on this as its just streaming to cout. + * + * @date September 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/containers/array.hpp" +#include "../../include/ecl/containers/push_and_pop.hpp" +#include "../../include/ecl/containers/stencil.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::Format; +using ecl::Hex; +using ecl::NoAlign; +using ecl::Stencil; + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Arrays" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Array int_array; + int_array << 1,2,3,4; + Array float_array; + float_array << 1,2,3.32235,-324; + Format< Array > format_array; +// Format< Array > format_array_float; + Array::Formatter format_array_float; + format_array_float.precision(3); + std::cout << format_array(int_array) << std::endl; + std::cout << format_array_float(float_array) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Dynamic Arrays" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Array float_array_dynamic(4); + Format< Array > format_array_dynamic_float; + format_array_dynamic_float.precision(3); + float_array_dynamic << 1,2,3.32235,-324; + std::cout << format_array_dynamic_float(float_array_dynamic) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Float Stencils" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Array float_array_under(20); + float_array_under << 1,2,3.32235,-324; + Format< Stencil< Array > > format_stencil; + format_stencil.precision(3); + std::cout << format_stencil(float_array_under.stencil(1,2)) << std::endl; + Array double_array_under(20); + double_array_under << 1,2,3.32235,-324; + Format< Stencil< Array > > format_double_stencil; + format_double_stencil.precision(3); + std::cout << format_double_stencil(double_array_under.stencil(1,2)) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Byte Arrays" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Array schar_array; + schar_array << 'a','b','c','d'; + Format< Array > format_sbytes; + std::cout << schar_array << std::endl; + std::cout << format_sbytes(schar_array) << std::endl; + std::cout << format_sbytes(schar_array.stencil(0,2)) << std::endl; + Array char_array; + char_array << 'a','b','c','d'; + Array::Formatter format_bytes; +// Format< Array > format_bytes; + std::cout << char_array << std::endl; + std::cout << format_bytes(char_array) << std::endl; + std::cout << format_bytes(char_array.stencil(0,2)) << std::endl; + Array uchar_array; + uchar_array << 0x01, 0x02, 0x03, 0x04; + Format< Array > format_ubytes; + Format format_uchar(-1,NoAlign,Hex); + std::cout << "[ "; + for ( unsigned int i = 0; i < uchar_array.size(); ++i ) { + std::cout << format_uchar(uchar_array[i]) << " "; + } + std::cout << "]" << std::endl; + std::cout << format_ubytes(uchar_array) << std::endl; + std::cout << format_ubytes(uchar_array.stencil(0,2)) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Push and Pop Byte Arrays" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Dynamic" << std::endl; + std::cout << std::endl; + + ecl::PushAndPop push_and_pop(4); + ecl::PushAndPop::Formatter format_push_pop; + //push_and_pop.resize(4); + push_and_pop.push_back(0x01); + std::cout << "Push 0x01: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x02); + std::cout << "Push 0x02: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x03); + std::cout << "Push 0x03: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x04); + std::cout << "Push 0x04: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.pop_front(); + std::cout << "Pop front: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.pop_front(); + std::cout << "Pop front: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x05); + std::cout << "Push 0x05: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x06); + std::cout << "Push 0x06: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x07); + std::cout << "Push 0x07: " << format_push_pop(push_and_pop) << std::endl; + push_and_pop.push_back(0x08); + std::cout << "Push 0x08: " << format_push_pop(push_and_pop) << std::endl; + + std::cout << "Size: " << push_and_pop.size() << std::endl; + std::cout << "[ "; + for ( unsigned int i = 0; i < push_and_pop.size(); ++i) { + std::cout << static_cast(push_and_pop[i]) << " "; + } + std::cout << "]" << std::endl; + + std::cout << std::endl; + std::cout << "Fixed" << std::endl; + std::cout << std::endl; + + ecl::PushAndPop push_and_pop_fixed; + ecl::PushAndPop::Formatter format_push_pop_fixed; + push_and_pop_fixed.push_back(0x01); + std::cout << "Push 0x01: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x02); + std::cout << "Push 0x02: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x03); + std::cout << "Push 0x03: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x04); + std::cout << "Push 0x04: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.pop_front(); + std::cout << "Pop front: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.pop_front(); + std::cout << "Pop front: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x05); + std::cout << "Push 0x05: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x06); + std::cout << "Push 0x06: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x07); + std::cout << "Push 0x07: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + push_and_pop_fixed.push_back(0x08); + std::cout << "Push 0x08: " << format_push_pop_fixed(push_and_pop_fixed) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + return 0; +} + diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_containers/src/test/CMakeLists.txt new file mode 100644 index 0000000..c85ed44 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/CMakeLists.txt @@ -0,0 +1,32 @@ +############################################################################### +# Google Tests Macro +############################################################################### + +macro(ecl_containers_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} + ecl_config::ecl_config + ecl_converters::ecl_converters + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits + ecl_utilities::ecl_utilities + ) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_containers_add_gtest(arrays) +ecl_containers_add_gtest(arrays_mem_check) +ecl_containers_add_gtest(container_converters) +ecl_containers_add_gtest(stencil) +ecl_containers_add_gtest(fifo) +ecl_containers_add_gtest(push_and_pop) + + diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays.cpp new file mode 100644 index 0000000..790fce8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays.cpp @@ -0,0 +1,178 @@ +/** + * @file /src/test/arrays.cpp + * + * @brief Unit Test for ecl::Array containers. + * + * @date September 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/containers/array.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::blueprints::ArrayFactory; +using ecl::blueprints::ConstantArray; +using ecl::StandardException; +using ecl::ContainerConcept; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ArrayMemCheckTests,constructors) { + Array array1 = Array::Constant(3); + EXPECT_EQ(3,array1[0]); + EXPECT_EQ(3,array1[1]); + EXPECT_EQ(3,array1[2]); + EXPECT_EQ(3,array1[3]); + Array array2 = ArrayFactory::Constant(4); + EXPECT_EQ(4,array2[0]); + EXPECT_EQ(4,array2[1]); + EXPECT_EQ(4,array2[2]); + EXPECT_EQ(4,array2[3]); + Array array3 = ConstantArray(3); + EXPECT_EQ(3,array3[0]); + EXPECT_EQ(3,array3[1]); + EXPECT_EQ(3,array3[2]); + EXPECT_EQ(3,array3[3]); +// std::cout << "Constant array [fixed] : " << array1 << std::endl; + Array darray1 = Array::Constant(4,3); + EXPECT_EQ(3,darray1[0]); + EXPECT_EQ(3,darray1[1]); + EXPECT_EQ(3,darray1[2]); + EXPECT_EQ(3,darray1[3]); +// std::cout << "Constant array [dynamic] : " << darray1 << std::endl; +} + +TEST(ArrayMemCheckTests,copyConstructors) { + + Array array1 = Array::Constant(3); + Array darray1 = Array::Constant(4,3); + + Array array2(array1); + Array darray2(darray1); + + EXPECT_EQ(3,array2[0]); + EXPECT_EQ(3,array2[1]); + EXPECT_EQ(3,array2[2]); + EXPECT_EQ(3,array2[3]); + + EXPECT_EQ(3,darray2[0]); + EXPECT_EQ(3,darray2[1]); + EXPECT_EQ(3,darray2[2]); + EXPECT_EQ(3,darray2[3]); +} + +TEST(ArrayMemCheckTests,blueprintAssignment) { + + Array array; + array = Array::Constant(3); + + EXPECT_EQ(3,array[0]); + EXPECT_EQ(3,array[1]); + EXPECT_EQ(3,array[2]); + EXPECT_EQ(3,array[3]); +} +TEST(ArrayMemCheckTests,commaInitialisation) { + + Array array; + Array darray(4); + array << 1,2,3,4; + darray << 1,2,3,4; + + EXPECT_EQ(1,array[0]); + EXPECT_EQ(2,array[1]); + EXPECT_EQ(3,array[2]); + EXPECT_EQ(4,array[3]); + + EXPECT_EQ(1,darray[0]); + EXPECT_EQ(2,darray[1]); + EXPECT_EQ(3,darray[2]); + EXPECT_EQ(4,darray[3]); +} +TEST(ArrayMemCheckTests,Accessors) { + + int j; + Array array; + Array darray(4); + array << 1,2,3,4; + darray << 1,2,3,4; + + j = array[2]; + EXPECT_EQ(3,j); + j = array.at(1); + EXPECT_EQ(2,j); + j = darray[2]; + EXPECT_EQ(3,j); + j = darray.at(1); + EXPECT_EQ(2,j); +} + +TEST(ArrayMemCheckTests,rangeChecking) { + + Array array = Array::Constant(3); + Array darray = Array::Constant(4,3); + bool result = false; + try { + array.at(10); + } catch ( StandardException &e ) { + result = true; +// std::cout << "Fixed:\n" << e.what() << std::endl; + } + EXPECT_TRUE(result); + result = false; + try { + darray.at(10); + } catch ( StandardException &e ) { + result = true; +// std::cout << "Dynamic:\n" << e.what() << std::endl; + } + EXPECT_TRUE(result); +} + +TEST(ArrayMemCheckTests,iterators) { + + Array array = Array::Constant(3); + Array::iterator iterator; + for ( iterator = array.begin(); iterator != array.end(); ++iterator ) { + EXPECT_EQ(3,*iterator); + } +} + +TEST(ArrayMemCheckTests,resize) { + Array darray = Array::Constant(4,3); + darray.resize(10); + darray << 0,1,2,3,4,5,6,7,8,9; + int i = 0; + Array::iterator iterator; + for ( iterator = darray.begin(); iterator != darray.end(); ++iterator ) { + EXPECT_EQ(i,*iterator); + ++i; + } + darray.clear(); +} + +TEST(ArrayMemCheckTests,concepts) { + typedef Array ByteArray; + ecl_compile_time_concept_check(ContainerConcept); + SUCCEED(); + // ecl_compile_time_concept_check(ContainerConcept>); // The macro won't let you do this (macro function syntax problem, not a c++ problem) +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays_mem_check.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays_mem_check.cpp new file mode 100644 index 0000000..e2872d8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/arrays_mem_check.cpp @@ -0,0 +1,240 @@ +/** + * @file /src/test/arrays_mem_check.cpp + * + * @brief Unit Test for ecl::Array containers. + * + * @date September 2009 + **/ +/***************************************************************************** +** Macros +*****************************************************************************/ + +#define ECL_MEM_CHECK_ARRAYS // Make sure we use mem checking arrays, not regular + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/containers/array.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::blueprints::ArrayFactory; +using ecl::blueprints::ConstantArray; +using ecl::StandardException; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ArrayMemCheckTests,constructors) { + Array array1 = Array::Constant(3); + EXPECT_EQ(3,array1[0]); + EXPECT_EQ(3,array1[1]); + EXPECT_EQ(3,array1[2]); + EXPECT_EQ(3,array1[3]); + Array array2 = ArrayFactory::Constant(4); + EXPECT_EQ(4,array2[0]); + EXPECT_EQ(4,array2[1]); + EXPECT_EQ(4,array2[2]); + EXPECT_EQ(4,array2[3]); + Array array3 = ConstantArray(3); + EXPECT_EQ(3,array3[0]); + EXPECT_EQ(3,array3[1]); + EXPECT_EQ(3,array3[2]); + EXPECT_EQ(3,array3[3]); +// std::cout << "Constant array [fixed] : " << array1 << std::endl; + Array darray1 = Array::Constant(4,3); + EXPECT_EQ(3,darray1[0]); + EXPECT_EQ(3,darray1[1]); + EXPECT_EQ(3,darray1[2]); + EXPECT_EQ(3,darray1[3]); +// std::cout << "Constant array [dynamic] : " << darray1 << std::endl; +} + +TEST(ArrayMemCheckTests,copyConstructors) { + + Array array1 = Array::Constant(3); + Array darray1 = Array::Constant(4,3); + + Array array2(array1); + Array darray2(darray1); + + EXPECT_EQ(3,array2[0]); + EXPECT_EQ(3,array2[1]); + EXPECT_EQ(3,array2[2]); + EXPECT_EQ(3,array2[3]); + + EXPECT_EQ(3,darray2[0]); + EXPECT_EQ(3,darray2[1]); + EXPECT_EQ(3,darray2[2]); + EXPECT_EQ(3,darray2[3]); +} + +TEST(ArrayMemCheckTests,blueprintAssignment) { + + Array array; + array = Array::Constant(3); + + EXPECT_EQ(3,array[0]); + EXPECT_EQ(3,array[1]); + EXPECT_EQ(3,array[2]); + EXPECT_EQ(3,array[3]); +} +TEST(ArrayMemCheckTests,commaInitialisation) { + + Array array; + Array darray(4); + array << 1,2,3,4; + darray << 1,2,3,4; + + EXPECT_EQ(1,array[0]); + EXPECT_EQ(2,array[1]); + EXPECT_EQ(3,array[2]); + EXPECT_EQ(4,array[3]); + + EXPECT_EQ(1,darray[0]); + EXPECT_EQ(2,darray[1]); + EXPECT_EQ(3,darray[2]); + EXPECT_EQ(4,darray[3]); +} +TEST(ArrayMemCheckTests,Accessors) { + + int j; + Array array; + Array darray(4); + array << 1,2,3,4; + darray << 1,2,3,4; + + j = array[2]; + EXPECT_EQ(3,j); + j = array.at(1); + EXPECT_EQ(2,j); + j = darray[2]; + EXPECT_EQ(3,j); + j = darray.at(1); + EXPECT_EQ(2,j); +} + +TEST(ArrayMemCheckTests,rangeChecking) { + + Array array = Array::Constant(3); + Array darray = Array::Constant(4,3); + bool result = false; + try { + array.at(10); + } catch ( StandardException &e ) { + result = true; +// std::cout << "Fixed:\n" << e.what() << std::endl; + } + EXPECT_TRUE(result); + result = false; + try { + darray.at(10); + } catch ( StandardException &e ) { + result = true; +// std::cout << "Dynamic:\n" << e.what() << std::endl; + } + EXPECT_TRUE(result); +} + +TEST(ArrayMemCheckTests,iterators) { + + Array array = Array::Constant(3); + Array::iterator iterator; + for ( iterator = array.begin(); iterator != array.end(); ++iterator ) { + EXPECT_EQ(3,*iterator); + } +} + +TEST(ArrayMemCheckTests,resize) { + Array darray = Array::Constant(4,3); + darray.resize(10); + darray << 0,1,2,3,4,5,6,7,8,9; + int i = 0; + Array::iterator iterator; + for ( iterator = darray.begin(); iterator != darray.end(); ++iterator ) { + EXPECT_EQ(i,*iterator); + ++i; + } + darray.clear(); +} + +TEST(ArrayMemCheckTests,bufferRuns) { + int *istart = NULL; + Array array_ok; array_ok << 1, 2, 3, 4; + Array array_under; array_under << 1, 2, 3, 4; + Array array_over; array_over << 1, 2, 3, 4; + +// std::cout << "Fixed Arrays" << std::endl; +// std::cout << "Array_under/over/ok: " << array_ok << std::endl; +// + +// std::cout << "Underrunning array_under." << std::endl; + istart = &array_under[0]; + for ( unsigned int i = 0; i < 3; ++i ) { + *(istart-i) = i; + } + +// std::cout << "Overrunning array_over." << std::endl; + istart = &array_over[0]; + for ( unsigned int i = 0; i < array_over.size() + 1; ++i ) { + *(istart+i) = i; + } +// +// std::cout << "Buffer results: " << std::endl; + EXPECT_TRUE(array_under.bufferUnderRun()); + EXPECT_FALSE(array_under.bufferOverRun()); + + EXPECT_TRUE(array_over.bufferOverRun()); + EXPECT_FALSE(array_over.bufferUnderRun()); + + EXPECT_FALSE(array_ok.bufferOverRun()); + EXPECT_FALSE(array_ok.bufferUnderRun()); + +// std::cout << "Dynamic Arrays" << std::endl; +// std::cout << std::endl; +// + Array darray_ok(4); darray_ok << 1, 2, 3, 4; + Array darray_under(4); darray_under << 1, 2, 3, 4; + Array darray_over(4); darray_over << 1, 2, 3, 4; + +// std::cout << "Array_under/over/ok: " << darray_ok << std::endl; +// +// std::cout << "Underrunning array_under." << std::endl; + istart = &darray_under[0]; + for ( unsigned int i = 0; i < darray_under.size()+1; ++i ) { + *(istart+i-1) = i; + } +// +// std::cout << "Overrunning array_over." << std::endl; + istart = &darray_over[0]; + for ( unsigned int i = 0; i < darray_over.size()+1; ++i ) { + *(istart+i) = i; + } + + EXPECT_TRUE(darray_under.bufferUnderRun()); + EXPECT_FALSE(darray_under.bufferOverRun()); + + EXPECT_TRUE(darray_over.bufferOverRun()); + EXPECT_FALSE(darray_over.bufferUnderRun()); + + EXPECT_FALSE(darray_ok.bufferOverRun()); + EXPECT_FALSE(darray_ok.bufferUnderRun()); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/container_converters.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/test/container_converters.cpp new file mode 100644 index 0000000..d8cadf6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/container_converters.cpp @@ -0,0 +1,147 @@ +/** + * @file /ecl_containers/src/test/converters.cpp + * + * @brief Unit test the stencil char byte array -> integral type converter. + * + * @date August 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/containers/array.hpp" +#include "../../include/ecl/containers/converters.hpp" +#include "../../include/ecl/containers/stencil.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::Stencil; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +bool debug_output = true; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +template +void print(const Container &byte_array) { + if( debug_output ) { + std::cout << byte_array << std::endl; + } +} + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +typedef Array ByteArray; +typedef Array DynamicByteArray; +typedef Stencil< Array > ByteStencil; +typedef Stencil< Array > DynamicByteStencil; +typedef Array SignedByteArray; +typedef Array DynamicSignedByteArray; +typedef Stencil< Array > SignedByteStencil; +typedef Stencil< Array > DynamicSignedByteStencil; +typedef Array UnsignedByteArray; +typedef Array DynamicUnsignedByteArray; +typedef Stencil< Array > UnsignedByteStencil; +typedef Stencil< Array > DynamicUnsignedByteStencil; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ConverterTests,fromArray) { + ByteArray byte_array; + byte_array << 0x01, 0x02, 0x03; + ecl::Converter toInt; + if( debug_output ) { std::cout << "Conversion: " << toInt(byte_array) << std::endl; } + EXPECT_EQ(197121,toInt(byte_array)); + UnsignedByteArray unsigned_byte_array; + unsigned_byte_array << 0x01, 0x02, 0x03; + ecl::Converter utoInt; + if( debug_output ) { std::cout << "Conversion: " << utoInt(unsigned_byte_array) << std::endl; } + EXPECT_EQ(197121,utoInt(unsigned_byte_array)); + SignedByteArray signed_byte_array; + signed_byte_array << 0x01, 0x02, 0x03; + ecl::Converter stoInt; + if( debug_output ) { std::cout << "Conversion: " << stoInt(signed_byte_array) << std::endl; } + EXPECT_EQ(197121,stoInt(signed_byte_array)); +} + +TEST(ConverterTests,toArray) { + // Only works for dynamic containers! + ecl::int32 i = 197121; + ecl::Converter toByteArray; + ecl::Converter toSignedByteArray; + ecl::Converter toUnsignedByteArray; + DynamicByteArray byte_array(4); + DynamicSignedByteArray signed_byte_array(4); + DynamicUnsignedByteArray unsigned_byte_array(4); + toByteArray(byte_array, i); + toSignedByteArray(signed_byte_array,i); + toUnsignedByteArray(unsigned_byte_array, i); + print(byte_array); + print(signed_byte_array); + print(unsigned_byte_array); + EXPECT_EQ(1,byte_array[0]); + EXPECT_EQ(2,byte_array[1]); + EXPECT_EQ(3,byte_array[2]); + EXPECT_EQ(1,signed_byte_array[0]); + EXPECT_EQ(2,signed_byte_array[1]); + EXPECT_EQ(3,signed_byte_array[2]); + EXPECT_EQ(1,unsigned_byte_array[0]); + EXPECT_EQ(2,unsigned_byte_array[1]); + EXPECT_EQ(3,unsigned_byte_array[2]); + +} +TEST(ConverterTests,fromStencil) { + ByteArray byte_array; + SignedByteArray signed_byte_array; + UnsignedByteArray unsigned_byte_array; + byte_array << 0x01, 0x02, 0x03; + signed_byte_array << 0x01, 0x02, 0x03; + unsigned_byte_array << 0x01, 0x02, 0x03; + ecl::Converter toInt; + ecl::Converter stoInt; + ecl::Converter utoInt; + int i = toInt(byte_array.stencil(0,2)); + int si = stoInt(signed_byte_array.stencil(0,2)); + int ui = utoInt(unsigned_byte_array.stencil(0,2)); + if( debug_output ) { std::cout << "Conversion: " << std::dec << i << std::endl; } + if( debug_output ) { std::cout << "Conversion: " << std::dec << si << std::endl; } + if( debug_output ) { std::cout << "Conversion: " << std::dec << ui << std::endl; } + EXPECT_EQ(513,i); // first two bytes only + EXPECT_EQ(513,si); // first two bytes only + EXPECT_EQ(513,ui); // first two bytes only +} +TEST(ConverterTests,toStencil) { + Array byte_array = Array::Constant(0x00); + Stencil< Array > stencil = byte_array.stencil(2,4); + ecl::Converter< Stencil< Array >, ecl::int32 > fromInt; + stencil = fromInt(stencil, 197121); + print(byte_array); + print(stencil); + EXPECT_EQ(1,stencil[0]); + EXPECT_EQ(2,stencil[1]); + EXPECT_EQ(3,stencil[2]); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/fifo.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/test/fifo.cpp new file mode 100644 index 0000000..94e344e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/fifo.cpp @@ -0,0 +1,196 @@ +/** + * @file /src/test/fifo.cpp + * + * @brief Unit Test for ecl::FiFo containers. + * + * @date Aug, 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/containers/array.hpp" +#include "../../include/ecl/containers/fifo.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::StandardException; +using ecl::ContainerConcept; +using ecl::FiFo; +/***************************************************************************** +** Tests +*****************************************************************************/ +TEST(FiFoTest,constructors) +{ + FiFo fifo(4, 2.0); + EXPECT_EQ(2.0, fifo[0]); + EXPECT_EQ(2.0, fifo[1]); + EXPECT_EQ(2.0, fifo[2]); + EXPECT_EQ(2.0, fifo[3]); +} + +TEST(FiFoTest, poping ) +{ + FiFo fifo(4); + for( int i=0; i<4; i++ ) + { + fifo.push_back( (double)i ); + } + + EXPECT_EQ(0.0, fifo[0]); + EXPECT_EQ(1.0, fifo[1]); + EXPECT_EQ(2.0, fifo[2]); + EXPECT_EQ(3.0, fifo[3]); +} + +/** + * @cond DO_NOT_DOXYGEN + */ +class movingAvg +{ +public: + movingAvg( const unsigned int widowsSize ) : + sum(0.0), + average(0.0), + windows_size(widowsSize), + first(true) + { + fifo.resize( windows_size ); + } + void reset() + { + fifo.fill(0); + sum = 0; + average = 0.0; + } + + void update( const double & incomingData ) + { + if( first ) + { + fifo.fill( incomingData ); + first = false; + } + + sum -= fifo[0]; + sum += incomingData; + fifo.push_back( incomingData ); + average = sum/(double)(windows_size); + } + double sum; + double average; + unsigned int windows_size; + FiFo fifo; + bool first; +}; + +/** + * @endcond + */ + + +TEST(FiFoTest, application ) +{ + movingAvg mavg( 10 ); + + for( int i=0; i<50; i++ ) + { + mavg.update( (double)i ); +// std::cout << mavg.average << std::endl; + } + + EXPECT_EQ(44.5, mavg.average ); +} + +/** + * @cond DO_NOT_DOXYGEN + */ + +/* + * @class + * treats differential of Gaussian. Usual objective is to detect the significant change of data incoming. + * you need just declaration of this class. and then please call update(..) function with your instance incoming data. + * it will return result of Differential of Gaussian. + * + * @note + * now, it build the kernel in contructor with hard coding. however we can formulize later. + */ +template +class DifferentialOfGaussian1D +{ +public: + DifferentialOfGaussian1D() + { + buildKernel(); + invalidate(); + } + + bool updateData( const N & incomingDatum, N & resultOfDOG ) + { + resultOfDOG = static_cast(0); + data.push_back( incomingDatum ); + for( int i=0; i data; + Array kernel; + int number_of_incoming; + + void buildKernel() + { + //build kernel + switch( KernelSize ) + { + case 5: + data.resize(KernelSize); + kernel.resize(KernelSize); + kernel[0] = 0.1179f; + kernel[1] = 0.2642f; + kernel[2] = 0.0f; + kernel[3] = -0.2642f; + kernel[4] = -0.1179f; + break; + + default: + std::cout << "class DifferentialOfGaussian1D +#include +#include "../../include/ecl/containers/array.hpp" +#include "../../include/ecl/containers/push_and_pop.hpp" + +/***************************************************************************** + ** Using + *****************************************************************************/ + +using ecl::Array; +using ecl::StandardException; +using ecl::ContainerConcept; +using ecl::PushAndPop; + +/***************************************************************************** + ** Tests + *****************************************************************************/ + +TEST(PushAndPopTests,constructors) +{ + PushAndPop pp_dynamic(4, 2); + EXPECT_EQ(2, pp_dynamic[0]); + EXPECT_EQ(2, pp_dynamic[1]); + EXPECT_EQ(2, pp_dynamic[2]); + EXPECT_EQ(2, pp_dynamic[3]); + + PushAndPop pp_fixed(2); + EXPECT_EQ(2, pp_fixed[0]); + EXPECT_EQ(2, pp_fixed[1]); + EXPECT_EQ(2, pp_fixed[2]); + EXPECT_EQ(2, pp_fixed[3]); +} + +TEST(PushAndPopTests, pop_and_push ) +{ + PushAndPop pp_dynamic(4); + for (int i = 0; i < 4; i++) + { + pp_dynamic.push_back((double)i); + } + + EXPECT_EQ(0.0, pp_dynamic[0]); + EXPECT_EQ(1.0, pp_dynamic[1]); + EXPECT_EQ(2.0, pp_dynamic[2]); + EXPECT_EQ(3.0, pp_dynamic[3]); + + pp_dynamic.pop_front(); + pp_dynamic.pop_front(); + EXPECT_EQ(2U, pp_dynamic.size()); + + // [0] always returns first data from the buffer + EXPECT_EQ(2.0, pp_dynamic[0]); + EXPECT_EQ(3.0, pp_dynamic[1]); +} + +TEST(PushAndPopTests, push_back_only ) +{ + PushAndPop pp; + for (unsigned int i = 0; i < 4; i++) + { + pp.push_back(i); + } + + EXPECT_EQ( 3U, pp.size()); + + for (unsigned int i = 4; i < 8; i++) + { + pp.push_back(i); + EXPECT_EQ( 3U, pp.size()); + } + + PushAndPop pp_dynamic(3, 1); + for (unsigned int i = 0; i < 4; i++) + { + pp_dynamic.push_back(i); + } + + EXPECT_EQ( 3U, pp_dynamic.size()); + + for (unsigned int i = 4; i < 8; i++) + { + pp_dynamic.push_back(i); + EXPECT_EQ( 3U, pp_dynamic.size()); + } +} + +TEST(PushAndPopTests, pop_front_only ) +{ + // fixed + PushAndPop pp; + for (unsigned int i = 0; i < 2; i++) + { + pp.push_back(i); + } + + EXPECT_EQ( 2U, pp.size()); + + for (unsigned int i = 0; i < 2; i++) + { + pp.pop_front(); + EXPECT_EQ( (2-1-i), pp.size()); + } + + // when you want to check pop-front, please enable below code manually +// for( unsigned int i=0; i<2; i++ ) +// { +// pp.pop_front(); +// EXPECT_EQ( 0, pp.size() ); +// } + +// dynamic + PushAndPop pp_dynamic(3, 1); + for (unsigned int i = 0; i < 2; i++) + { + pp_dynamic.push_back(i); + } + + EXPECT_EQ( 2U, pp_dynamic.size()); + + for (unsigned int i = 0; i < 2; i++) + { + pp_dynamic.pop_front(); + EXPECT_EQ( (2-1-i), pp_dynamic.size()); + } + + // when you want to check pop-front, please enable below code manually +// for( unsigned int i=0; i<2; i++ ) +// { +// pp_dynamic.pop_front(); +// EXPECT_EQ( 0, pp_dynamic.size() ); +// } +} + +TEST(PushAndPopTests,concepts) +{ + typedef PushAndPop UnsignedByteBuffer; + ecl_compile_time_concept_check (ContainerConcept ); + typedef PushAndPop ByteBuffer; + ecl_compile_time_concept_check (ContainerConcept ); + SUCCEED(); + // ecl_compile_time_concept_check(ContainerConcept>); // The macro won't let you do this (macro function syntax problem, not a c++ problem) +} + + +/***************************************************************************** + ** Main program + *****************************************************************************/ + +int main(int argc, char **argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_containers/src/test/stencil.cpp b/ros2_ws/src/ecl_core/ecl_containers/src/test/stencil.cpp new file mode 100644 index 0000000..48b80a9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_containers/src/test/stencil.cpp @@ -0,0 +1,172 @@ +/** + * @file /src/test/stencil.cpp + * + * @brief Unit Test for the @ref ecl::Stencil "Stencil" class. + * + * @date March, 2010 + **/ +/***************************************************************************** +** Macros +*****************************************************************************/ + +// Make sure we enter debug mode. +#ifdef NDEBUG + #undef NDEBUG +#endif +#ifdef ECL_NDEBUG + #undef ECL_NDEBUG +#endif + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +//#include +#include "../../include/ecl/containers/array.hpp" +#include "../../include/ecl/containers/stencil.hpp" +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::Array; +using ecl::Stencil; +using ecl::UnsignedByteContainerConcept; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +typedef Stencil< Array > FixedStencil; +typedef Stencil< Array > DynamicStencil; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(StencilTests,construction) { + + Array array; + Array darray(5); + array << 1,2,3,4,5; + darray << 6,7,8,9,10; + + FixedStencil stencil = array.stencil(1,3); // 2,3.4 + DynamicStencil dstencil(darray,darray.begin()+1,darray.begin()+4); // 7,8,9 + EXPECT_EQ(2,stencil[0]); + EXPECT_EQ(3,stencil[1]); + EXPECT_EQ(4,stencil[2]); + EXPECT_EQ(7,dstencil[0]); + EXPECT_EQ(8,dstencil[1]); + EXPECT_EQ(9,dstencil[2]); +} + +TEST(StencilTests,badConstruction) { + + Array darray(5); + darray << 6,7,8,9,10; + + bool result = false; + try { + DynamicStencil bad_stencil(darray,darray.begin()+1,darray.begin()+9); + } catch ( StandardException &e ) { + result = true; + } + EXPECT_TRUE(result); +} + +TEST(StencilTests,badIndexing) { + + Array darray(5); + darray << 6,7,8,9,10; + + DynamicStencil dstencil(darray,darray.begin()+1,darray.begin()+4); // 7,8,9 + darray.resize(3); + darray << 6,7,8; + bool result = false; + try { + dstencil[2]; // Even something that looks good will generally fail as the memory has moved. + dstencil[4]; + } catch ( StandardException &e ) { + result = true; + } + EXPECT_TRUE(result); +} +TEST(StencilTests,modifying) { + Array array; + Array darray(5); + array << 1,2,3,4,5; + darray << 6,7,8,9,10; + FixedStencil stencil = array.stencil(1,3); // 2,3.4 + stencil.resettle(0,2); // 1,2 + EXPECT_EQ(1,stencil[0]); + EXPECT_EQ(2,stencil[1]); + stencil = array.stencil(1,4); // 2,3,4,5 + EXPECT_EQ(2,stencil[0]); + EXPECT_EQ(3,stencil[1]); + EXPECT_EQ(4,stencil[2]); + EXPECT_EQ(5,stencil[3]); +} + +TEST(StencilTests,concepts) { + + typedef Array ByteArray; + typedef Stencil ByteStencil; + + // ecl_compile_time_concept_check(ecl::concepts::ByteContainer); // this one fails + ecl_compile_time_concept_check(UnsignedByteContainerConcept); + ecl_compile_time_concept_check(UnsignedByteContainerConcept); + SUCCEED(); +} + +TEST(StencilTests,byteStrings) { + + std::string str("dude"); + Stencil stencil( str, str.begin(), str.end() ); + EXPECT_EQ(4U,stencil.size()); + EXPECT_EQ('d',stencil[0]); + EXPECT_EQ('u',stencil[1]); + EXPECT_EQ('d',stencil[2]); + EXPECT_EQ('e',stencil[3]); +// for ( unsigned int i = 0; i < stencil.size(); ++i ) { +// std::cout << i << ": " << stencil[i] << std::endl; +// } + + SUCCEED(); +} + +TEST(StencilTests,unsignedCharArrays) { + + //unsigned char buffer[4] = { 0xff, 0x00, 0x01, 0x02 }; + unsigned char buffer[4]; + Stencil stencil( buffer, 4, buffer, buffer + 4); + stencil << 0xff, 0x00, 0x01, 0x02; + EXPECT_EQ(4U,stencil.size()); + EXPECT_EQ(255,stencil[0]); + EXPECT_EQ(0,stencil[1]); + EXPECT_EQ(1,stencil[2]); + EXPECT_EQ(2,stencil[3]); +// std::cout << std::hex; +// for ( unsigned int i = 0; i < stencil.size(); ++i ) { +// std::cout << i << ": " << static_cast(stencil[i]) << std::endl; +// } +// std::cout << std::dec; + + SUCCEED(); +} + + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/.cproject b/ros2_ws/src/ecl_core/ecl_converters/.cproject new file mode 100644 index 0000000..c4370a7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/.cproject @@ -0,0 +1,335 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + tests + true + true + true + + + make + clean + true + true + true + + + make + + examples + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/.project b/ros2_ws/src/ecl_core/ecl_converters/.project new file mode 100644 index 0000000..ba4cea8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/.project @@ -0,0 +1,79 @@ + + + ecl_converters + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_converters/CHANGELOG.rst new file mode 100644 index 0000000..c7b0a3c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/CHANGELOG.rst @@ -0,0 +1,12 @@ +========= +Changelog +========= + +0.61.18 (2017-06-26) +-------------------- +* disable byte array failed size test in release mode (debug exceptions only) + +0.61.4 (2015-10-10) +------------------- +* fix byte array converter error handling in release mode + diff --git a/ros2_ws/src/ecl_core/ecl_converters/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/CMakeLists.txt new file mode 100644 index 0000000..14a2032 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/CMakeLists.txt @@ -0,0 +1,87 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_converters) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_concepts REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_mpl REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Platform Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + ecl_concepts::ecl_concepts + ecl_config::ecl_config + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_concepts + ecl_config + ecl_errors + ecl_exceptions + ecl_mpl + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..6446013 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(converters) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters.hpp new file mode 100644 index 0000000..cded652 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters.hpp @@ -0,0 +1,35 @@ +/** + * @file /include/ecl/converters.hpp + * + * @brief Type conversion functors. + * + * Collates all classes related to type conversions. + * + * @date January 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_HPP_ +#define ECL_CONVERTERS_HPP_ + +/***************************************************************************** +** Primary Templates +*****************************************************************************/ + +#include "converters/converter.hpp" + +/***************************************************************************** +** Specialisations +*****************************************************************************/ + +#include "converters/to_byte_array.hpp" +#include "converters/from_byte_array.hpp" +#include "converters/converter.hpp" +#include "converters/char.hpp" +#include "converters/integers.hpp" +#include "converters/char_strings.hpp" +#include "converters/string.hpp" + +#endif /*ECL_UTILITIES_CONVERTERS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/CMakeLists.txt new file mode 100644 index 0000000..4b449e0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/converters) diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char.hpp new file mode 100644 index 0000000..09139f7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char.hpp @@ -0,0 +1,122 @@ +/** + * @file /include/ecl/converters/char.hpp + * + * @brief Type conversions to a readable (ascii) char type. + * + * A variety of functors that do type conversion to a readable (ascii) char + * type. + * + * @date April 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_CHAR_HPP_ +#define ECL_CONVERTERS_CHAR_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "converter.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Character Converter Interface +*****************************************************************************/ +/** + * @brief Converts unsigned ints into readable (ascii) characters. + * + * @sa Converter + **/ +template <> +class Converter : public converters::ConverterBase { +public: + virtual ~Converter() {} + + /** + * Converts a single unsigned int into a char type. A similar function is used in + * stlsoft. + * + * This throws an exception and/or configures the error() + * function for this converter if the input digit is not a char digit ['0'-'9'] + * + * @param input : the input digit to be converted. + * @return char : the character representation of the digit. + * + * @exception : throws if input is not a char digit ['0'-'9'] (debug mode only). + **/ + char operator()(const unsigned int &input) { + if ( input > 9 ) { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + } + return ('0'+ input%10); // Copy the char back. + } +}; +/** + * @brief Converts ints into readable (ascii) characters. + * + * @sa Converter + **/ +template <> +class Converter : public converters::ConverterBase { +public: + virtual ~Converter() {} + + /** + * Converts a single int into a char type. A similar function is used in + * stlsoft. + * + * This throws an exception and/or configures the error() + * function for this converter if the input digit is not a char digit ['0'-'9'] + * + * @param input : the input digit to be converted. + * @return char : the character representation of the digit. + * + * @exception : throws if input is not a char digit ['0'-'9'] (debug mode only). + **/ + char operator()(const int &input) { + if ( ( input < 0 ) || (input > 9) ) { + ecl_debug_throw(StandardException(LOC,OutOfRangeError)); + error_handler = OutOfRangeError; + } + return ('0'+ input%10); // Copy the char back. + } +}; + +/***************************************************************************** + * Char Converter Family + ****************************************************************************/ +/** + * @brief Family of converters to char. + * + * This groups all the char converters of fundamental types into a single + * cohesive superclass. + * + * @sa Converter + **/ +template <> +class Converter : + public Converter, + public Converter +{ + public: + virtual ~Converter() {} + + using Converter::operator(); + using Converter::operator(); +}; + +} // namespace ecl + + +#endif /*ECL_CONVERTERS_CHAR_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char_strings.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char_strings.hpp new file mode 100644 index 0000000..7445cf3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/char_strings.hpp @@ -0,0 +1,909 @@ +/** + * @file /include/ecl/converters/char_strings.hpp + * + * @brief Type conversions to character strings. + * + * A variety of functors that do type conversion to character + * strings. These are designed to be very fast, unlike the string converters. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_CONVERT_CHAR_STRINGS_HPP_ +#define ECL_CONVERTERS_CONVERT_CHAR_STRINGS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // vsnprintf +#include //strcat +#include +#include "converter.hpp" +#include +#include +#include + +#if _MSC_VER +#define snprintf _snprintf +#endif + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @cond DO_NOT_DOXYGEN + */ +namespace converters { + +/***************************************************************************** +** Inheritable Buffer Interface +*****************************************************************************/ +/** + * @brief An inheritable buffer class for the character string converters. + * + * Provides a buffer interface for the character string classes. Buffers can + * either be created internally, or provide from without. Any inheriting class + * should provide constructors that will initialise the inherited buffer + * appropriately. + **/ +class CharStringBuffer : public ConverterBase { + protected: + /****************************************** + ** C&D's + *******************************************/ + /** + * @brief Initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + CharStringBuffer(char* begin, char* end) : buffer_begin(begin),buffer_end(end),delete_buffer(false) {} + /** + * @brief Initialises with an internal buffer. + * + * If allocation of the internal buffer fails, it will throw an exception (debug mode only) or set + * the error handler with a MemoryError. + * + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if the allocation for the internal buffer failed (debug mode only). + **/ + CharStringBuffer(int buffer_size = 250) : delete_buffer(true) { + buffer_begin = new (std::nothrow) char[buffer_size]; + *(buffer_begin + buffer_size - 1) = '\0'; + buffer_end = buffer_begin + buffer_size - 1; + if ( buffer_begin == NULL ) { + ecl_debug_throw(ecl::StandardException(LOC,ecl::MemoryError,"Failed to allocate memory for the char string buffer.")); + error_handler = ecl::MemoryError; + } + } + /** + * Default destructor. If a buffer was initialised by this object, it is deleted. + **/ + virtual ~CharStringBuffer() { + if(delete_buffer) { + delete[] buffer_begin; + delete_buffer = false; + } + } + + char *buffer_begin; + char *buffer_end; + bool delete_buffer; +}; + +/***************************************************************************** +** Character String Converter Utilities +*****************************************************************************/ +/** + * @brief Fast internal utility function that converts an unsigned integral and puts it on the buffer. + * + * This function uses an assert (debug mode only) at the end of processing to check the buffer's + * range has not been exceeded. + * + * @param number : The unsigned number to be converted. + * @param buffer_begin : start of the buffer to be used. + * @param buffer_end : end of the buffer to be used. + * @return char* : a pointer to the buffer (NULL if the buffer was exceeded). + **/ +template +char* convertUnsignedIntegral(Number number, char* buffer_begin, char* buffer_end) +{ + *(buffer_end) = '\0'; // Set to the null terminator + Number lsd; + char* str_ptr = buffer_end; + + do { + lsd = static_cast(number % 10); // Determine the least significant digit. + number = static_cast(number / 10); // Deal with next most significant. + --str_ptr; + if ( str_ptr < buffer_begin ) { return NULL; } + *str_ptr = '0'+lsd; + } while (number != 0); + return str_ptr; +} + +/** + * Very fast internal utility function that converts a signed integral and puts it on the buffer. + * @param number : the unsigned number to be converted. + * @param buffer_begin : start of the buffer to be used. + * @param buffer_end : end of the buffer to be used. + * @return char* : a pointer to the buffer. + * + **/ +template +char* convertSignedIntegral(const Number &number, char* buffer_begin, char* buffer_end) +{ + typedef typename Unsigned::type UnsignedNumber; + + char *s; + if ( number >= 0 ) { + s = convertUnsignedIntegral(static_cast(number),buffer_begin,buffer_end); + } else { + s = convertUnsignedIntegral(static_cast(-1*number),buffer_begin+1,buffer_end); + if (s == NULL) { + return NULL; + } + --s; + *s = '-'; + } + return s; +} + + +} // namespace converters + +/** + * @endcond + */ + +/***************************************************************************** +** Char String Converters [char] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if the allocation for the internal buffer failed (debug mode only). + **/ + Converter(int buffer_size = 250) : + converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts a char to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const char &input) { + return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); + } +}; +/***************************************************************************** +** Char String Converters [unsigned char] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if the allocation for the internal buffer failed (debug mode only). + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts an unsigned char to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const unsigned char &input){ return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [short] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts a short to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const short &input){ return converters::convertSignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [unsigned short] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts an unsigned short to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const unsigned short &input){ return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; + +/***************************************************************************** +** Char String Converters [int] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /** + * Converts a int to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const int &input){ return converters::convertSignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [unsigned int] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts an unsigned int to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const unsigned int &input){ return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; + +/***************************************************************************** +** Char String Converters [long] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * Converts a long to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const long &input){ return converters::convertSignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [unsigned long] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /** + * Converts an unsigned long to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const unsigned long &input){ return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [long long] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) {} + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) {} + + virtual ~Converter() {} + + /** + * Converts a long long to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const long long &input){ return converters::convertSignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [unsigned long long] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * This class uses a character buffer for the character strings that it + * generates. Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) { + } + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) { + } + + virtual ~Converter() {} + + /** + * Converts an unsigned long long to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const unsigned long long &input){ return converters::convertUnsignedIntegral(input,this->buffer_begin,this->buffer_end); } +}; +/***************************************************************************** +** Char String Converters [float] +*****************************************************************************/ +/** + * @brief Conversion to text format with character strings. + * + * This class uses a character buffer for the character strings that it + * generates. If your buffer is not long enough, this will just + * truncate the output to fit the buffer. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * @brief Initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) { + format_specifier[0] = '%'; + format_specifier[1] = '.'; + format_specifier[2] = 'x'; + format_specifier[3] = 'f'; + format_specifier[4] = 'f'; + format_specifier[5] = '\0'; + } + /** + * @brief Initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) { + format_specifier[0] = '%'; + format_specifier[1] = '.'; + format_specifier[2] = 'x'; + format_specifier[3] = 'f'; + format_specifier[4] = 'f'; + format_specifier[5] = '\0'; + } + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * @brief Convert the specified double to int. + * + * Converts an double to a char string held in the converter's buffer. + * I'd like to one day have my own (perhaps faster?) or refined + * implementation of snprintf but it will do for now. + * + * @param input : input value to be converted. + * @param precision : number of decimal places to show (-1 to automagically allocate). + * @returns char* : output text string. + **/ + char* operator ()(const float &input, const int& precision = -1){ + if ( precision < 0 ) { + format_specifier[1] = 'f'; + format_specifier[2] = '\0'; + } else if ( precision < 10 ) { + format_specifier[1] = '.'; + format_specifier[2] = '0'+precision; + format_specifier[3] = 'f'; + format_specifier[4] = '\0'; + } else if ( precision < 20 ) { + format_specifier[1] = '.'; + format_specifier[2] = '1'; + format_specifier[3] = '0'+(precision - 10); + format_specifier[4] = 'f'; + } else { + format_specifier[1] = '.'; + format_specifier[2] = '2'; + format_specifier[3] = '0'; + format_specifier[4] = 'f'; + } + + snprintf(this->buffer_begin, this->buffer_end-this->buffer_begin, format_specifier, input); + return this->buffer_begin; +// return converters::convertDecimal<32>(input,this->buffer_begin,this->buffer_end); + } + private: + char format_specifier[6]; +}; +/***************************************************************************** +** Char String Converters [double] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * This class uses a character buffer for the character strings that it + * generates. If your buffer is not long enough, this will just + * truncate the output to fit the buffer. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * @brief Initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) { + format_specifier[0] = '%'; + format_specifier[1] = '.'; + format_specifier[2] = 'x'; + format_specifier[3] = 'f'; + format_specifier[4] = 'f'; + format_specifier[5] = '\0'; + } + /** + * @brief Initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) { + format_specifier[0] = '%'; + format_specifier[1] = '.'; + format_specifier[2] = 'x'; + format_specifier[3] = 'f'; + format_specifier[4] = 'f'; + format_specifier[5] = '\0'; + } + + virtual ~Converter() {} + + /****************************************** + ** Converters + *******************************************/ + /** + * @brief Convert the specified double to int. + * + * Converts an double to a char string held in the converter's buffer. + * I'd like to one day have my own (perhaps faster?) or refined + * implementation of snprintf but it will do for now. + * + * @param input : input value to be converted. + * @param precision : number of decimal places to show (-1 to automagically allocate). + * @returns char* : output text string. + **/ + char* operator ()(const double &input, const int& precision = -1){ + if ( precision < 0 ) { + format_specifier[1] = 'f'; + format_specifier[2] = '\0'; + } else if ( precision < 10 ) { + format_specifier[1] = '.'; + format_specifier[2] = '0'+precision; + format_specifier[3] = 'f'; + format_specifier[4] = '\0'; + } else if ( precision < 20 ) { + format_specifier[1] = '.'; + format_specifier[2] = '1'; + format_specifier[3] = '0'+(precision - 10); + format_specifier[4] = 'f'; + } else { + format_specifier[1] = '.'; + format_specifier[2] = '2'; + format_specifier[3] = '0'; + format_specifier[4] = 'f'; + } + snprintf(this->buffer_begin, this->buffer_end-this->buffer_begin, format_specifier, input); + return this->buffer_begin; +// return converters::convertDecimal<64>(input,this->buffer_begin,this->buffer_end); + } + private: + char format_specifier[6]; +}; +/***************************************************************************** +** Char String Converters [bool] +*****************************************************************************/ +/** + * @brief Fast conversion to text format with character strings. + * + * Provides a fast conversion to text using character strings. + * + * Unlike some of the numeric converters, this uses an internal character + * buffer as the output is of known lengths (outputs are either 'true' or 'false'). + * Ensure your converter does not go out of scope while using + * the character strings otherwise your character strings will end up + * pointing at rubbish. + * + * @sa Converter + **/ +template<> +class Converter : public virtual converters::CharStringBuffer { + public: + /** + * Constructor that initialises with an internal buffer. + **/ + Converter() : converters::CharStringBuffer(6) {} + + virtual ~Converter() {} + + /** + * Converts a bool to a char string held in the converter's buffer. + * @param input : input value to be converted. + * @returns char* : output text string. + **/ + char* operator ()(const bool &input){ + *buffer_begin = '\0'; + input ? strcat(buffer_begin,"true") : strcat (buffer_begin,"false"); + return buffer_begin; + } +}; + +/***************************************************************************** + * Char String Converter Family + ****************************************************************************/ +/** + * @brief Family of converters to character strings. + * + * This groups all the character string converters of fundamental types into a single + * cohesive superclass. This is often more convenient, especially as each converter + * will utilise a single buffer. This is important if doing many different character + * string conversions in the same scope. + * + * @sa Converter + **/ +template <> +class Converter : + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter, + public Converter +{ + public: + /** + * Constructor that initialises with an external buffer. + * @param begin : character pointer that points to the start of the external buffer. + * @param end : character pointer that points to the end of the external buffer. + **/ + Converter(char* begin, char* end) : converters::CharStringBuffer(begin,end) { + } + /** + * Constructor that initialises with an internal buffer. + * @param buffer_size : size of the buffer to create - if not supplied it initialises a buffer of size 250. + * + * @exception StandardException : throws if it failed to allocate memory for the internal buffer [debug mode only]. + **/ + Converter(int buffer_size = 250) : converters::CharStringBuffer(buffer_size) { + } + + virtual ~Converter() {} + + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); + using Converter::operator(); +}; + +} // namespace ecl + +#endif /*ECL_CONVERTERS_CONVERT_CHAR_STRINGS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/converter.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/converter.hpp new file mode 100644 index 0000000..976a3cf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/converter.hpp @@ -0,0 +1,115 @@ +/** + * @file /include/ecl/converters/converter.hpp + * + * @brief Primary templates for the family of converter classes. + * + * @date April, 2009 + **/ +/***************************************************************************** +** PreProcessor +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_CONVERTER_HPP_ +#define ECL_CONVERTERS_CONVERTER_HPP_ + +/***************************************************************************** +** Include +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +/** + * @cond DO_NOT_DOXYGEN + */ +namespace converters { + +class ConverterBase { +public: + ConverterBase() : error_handler(ecl::NoError) {}; + virtual ~ConverterBase() {} /** @brief Required virtual destructor **/ + virtual Error error() const { return error_handler; } +protected: + Error error_handler; +}; +} // namespace converters +/** + * @endcond + */ +/***************************************************************************** +** Converter Interface +*****************************************************************************/ +/** + * @brief Primary template and general fallback for converter classes. + * + * This is the primary template for all converter classes. It + * also provides a default fallback for a single type conversion where both + * input and output types are defined in as template parameters. + * + * @sa Converter + * + **/ +template +class Converter : public converters::ConverterBase { +public: + virtual ~Converter() {} + Output operator()(const Input &input); +}; + +/** + * @brief Primary template for the output-designated only converters. + * + * This is the primary template for the sub-family of converters which + * only designate the output in the template argument. These are + * designed to incorporate a group of conversions to the specified output type + * (convenience class). + **/ +template +class Converter : public converters::ConverterBase { +public: + virtual ~Converter() {} + + template + Output operator()(const Input &input); +}; + +/***************************************************************************** +** Converter Implementation +*****************************************************************************/ +/** + * The default fallback for converting a specific input type to a specific + * output type. This looks inside the output template + * argument's class for the required converter. + * + * @param input : the input value to be converted. + * @return Output : the converted type. + **/ +template +Output Converter::operator ()(const Input &input) +{ + return typename Output::Converter()(input); +} + +/** + * The generalised fallback for converting various input types to a + * specific output type. This looks inside the output template + * argument's class for the required converter. + * + * @param input : the input value to be converted. + * @return Output : the converted type. + **/ +template +template +Output Converter::operator ()(const Input &input) +{ + return typename Output::Converter()(input); +} + +} // namespace ecl + + +#endif /* ECL_CONVERTERS_CONVERTER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/from_byte_array.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/from_byte_array.hpp new file mode 100644 index 0000000..54cefbf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/from_byte_array.hpp @@ -0,0 +1,146 @@ +/** + * @file /include/ecl/converters/from_byte_array.hpp + * + * @brief Converts byte arrays to integral types. + * + * @date August 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONVERTERS_CONVERTERS_FROM_BYTE_ARRAY_HPP_ +#define ECL_CONVERTERS_CONVERTERS_FROM_BYTE_ARRAY_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "converter.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ +/** + * @cond DO_NOT_DOXYGEN + */ +namespace converters +{ + +/***************************************************************************** + ** Interface + *****************************************************************************/ + +/** + * @brief Byte array to integral type converter. + * + * This class is not meant to be used directly, rather it is a + * simple base class for specialisations. This is kept separate because it + * the generic template type calls will clash with the default + * converter template specification. Specialise this for + * the various classes we actually want to use + * (i.e. see Converter> etc.) + */ +template +class ECL_PUBLIC FromByteArray : public ConverterBase +{ +public: + /** + * Converts from a byte array container to an integral type. + * The bytes are ordered from least significant to most + * significant (little-endian). + * + * This function has compile time asserts to check that + * the 'to' type is integral, also a compile time concept + * check that the byte array is a byte container and also + * handles the error case when the byte array size doesn't + * exactly match the integral type size (throws an + * exception in debug mode and flags error() with a + * ConversionError. + * + * @param byte_array : the input byte array container. + * @return int : the integer representation of the digit. + * @exception StandardException: throws if byte array size doesn't match integral type size (in bytes) [debug mode only]. + **/ + Integral operator()(const ByteArray &byte_array) + { + /********************* + ** Checks + **********************/ + ecl_compile_time_concept_check(ByteContainerConcept); + ecl_compile_time_assert(is_integral::value); + if (byte_array.size() > ecl::numeric_limits::bytes) + { + ecl_debug_throw( + StandardException(LOC,ConversionError,"The byte array is too long for the integral type specified.")); + error_handler = ConversionError; + } + /********************* + ** Method + **********************/ + typename ecl::Unsigned::type unsigned_value = 0; + for (unsigned int i = 0; i < byte_array.size(); ++i) + { + unsigned_value |= static_cast(byte_array[i]) << 8 * i; + } + if (ecl::is_signed::value) + { + Integral value = static_cast(unsigned_value); + return value; + } + else + { + return unsigned_value; + } + } + /** + * @brief Required virtual destructor. + */ + virtual ~FromByteArray() {} +}; + +} // namespace converters + +/** + * @endcond + */ + +/** + * @brief Specialisation for the vector container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : + public converters::FromByteArray > +{ +}; +/** + * @brief Specialisation for the vector container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray > +{ +}; +/** + * @brief Specialisation for the vector container based FromByteArray converter. + */ +template +class ECL_PUBLIC Converter > : public converters::FromByteArray > +{ +}; + +} // namespace ecl + +#endif /* ECL_CONVERTERS_CONVERTERS_FROM_BYTE_ARRAY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/integers.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/integers.hpp new file mode 100644 index 0000000..f8fc62d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/integers.hpp @@ -0,0 +1,228 @@ +/** + * @file /include/ecl/converters/integers.hpp + * + * @brief Integer conversion functors (shims). + * + * A variety of functors (shims) that do type conversion to integer types. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_CONVERTERS_INTEGERS_HPP_ +#define ECL_CONVERTERS_CONVERTERS_INTEGERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "converter.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +/** + * @brief Conversion from a string to an integer type. + * + * Very quick conversions to an int type. These are partially based on the + * stlsoft techniques. + **/ +template <> +class Converter : public converters::ConverterBase { +public: + virtual ~Converter() {}; + /** + * @brief Converts a string to an integer type. + * + * This throws an exception and/or configures the error() + * function for this converter if the input does not consist + * purely of the appropriate digits for an integer. + * + * @param input : the input string to be converted. + * @return int : the integer representation, INT_MIN on error. + * @exception StandardException : throws if conversion failed (debug mode only). + **/ + int operator()(const std::string &input) { + int i; + std::istringstream stream(input); + char c; + if ( !( stream >> i ) || (stream.get(c))) { // Second part checks that there isn't leftover characters + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + } + return i; + } +}; +/** + * @brief Conversion from a char to an integer type. + * + * This is of course restricted to characters ['0'-'9']. + * + * @exception StandardException : throws if character is outside the range ['0'-'9']. + **/ +template <> +class Converter : public converters::ConverterBase { +public: + /** + * @brief Converts a char to an integer type. + * + * This throws an exception and/or configures the error() + * function for this converter if the input is not a char digit ['0'-'9']. + * + * @param c : the input char to be converted [0-9]. + * @return int : the integer representation of the digit (-1 on failure). + * @exception StandardException : throws if conversion failed (debug mode only). + **/ + int operator()(char c) { + if ( ( c < '0' ) || (c > '9') ) { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + } + return static_cast(c - '0'); + } +}; + +/** + * @brief Conversion from a byte array to an integer type. + * + * Converts from a byte array to an integer type. Be sure that the length of + * the byte array is large enough for the required transformation to an integer. + * + * @sa Converter + **/ +template <> +class Converter { +private: + Converter() { + // This class is being depracated! Use the byte array converters instead (converters/from_byte_array.hpp) + } +public: +// /** +// * Converts a byte array to an integer type. The bytes are ordered from +// * least significant to most significant (little-endian). Warning: the +// * byte array must be the same size as the integer that it is being +// * converted to (i.e. usually 4 bytes). +// * +// * @param byte_array : the input string to be converted. +// * @return int : the integer representation of the digit. +// **/ +// int operator()(const unsigned char* byte_array) { +// int value = 0; +// for (unsigned int i = 0; i < sizeof(int); ++i ) { +// value |= *(byte_array+i) << 8*i; +// } +// return value; +// } +}; +/** + * @brief Conversion from a char array to an integer type. + * + * Converts from a char string to an integer type. Be sure that the length of + * the char array is large enough for the required transformation to an integer. + * + * @sa Converter + **/ +template <> +class Converter : public converters::ConverterBase { +private: + Converter() { + // This class is being depracated! Use the byte array converters instead (converters/from_byte_array.hpp) + } +public: +// NEW +// /** +// * Converts a c string to an integer type. This converts +// * ascii characters to an integer, not bytes to integer. For that +// * see the byte array converters in this package. +// * +// * @todo Add checks to ensure the range of int is not exceeded. +// * +// * @param c_str : the input string to be converted. +// * @return int : the integer representation of the digit. +// * +// * @exception : throws in debug mode if a non-digit char is found (debug mode only). +// **/ +// int operator()(const char* c_str) { +// int value = 0; +// bool negative_flag = false; +// unsigned int starting_index = 0; +// if ( c_str[0] == '-' ) { +// negative_flag = true; +// starting_index = 1; +// } +// size_t length = ::strlen(c_str); +// int multiplier = 1; +// for ( unsigned int i = length-1; i >= starting_index; --i ) { +// if ( ( c_str[i] < '0' ) || (c_str[i] > '9') ) { +// ecl_debug_throw(StandardException(LOC,ConversionError)); +// error_handler = ConversionError; +// } +// value += multiplier*static_cast(c_str[i] - '0'); +// multiplier *= 10; +// } +// if ( negative_flag) { +// value *= -1; +// } +// return value; +// } +// OLD +// /** +// * Converts a char array to an integer type. The bytes are ordered from +// * least significant to most significant (little-endian). Warning: the +// * byte array must be the same size as the integer that it is being +// * converted to (i.e. usually 4 bytes). +// * +// * @param byte_array : the input string to be converted. +// * @return int : the integer representation of the digit. +// **/ +// int operator()(const char* byte_array) { +// if ( ::strlen(byte_array) != sizeof(int) ) { +// ecl_debug_throw(StandardException(LOC,InvalidInputError,"Input char string length is too large/small for conversion to int.")); +// } +// int value = 0; +// for (unsigned int i = 0; i < sizeof(int); ++i ) { +// value |= static_cast(*(byte_array+i)) << 8*i; +// } +// return value; +// } +}; + +/** + * @brief Conversions to integers. + * + * This groups all the string converters of fundamental types into a single + * cohesive superclass. At times, this is more convenient than using the + * string converters individually. + * + * @sa Converter + **/ +template <> +class Converter : + public Converter, + public Converter +// public Converter, +// public Converter +{ + public: + using Converter::operator(); + using Converter::operator(); +// using Converter::operator(); +// using Converter::operator(); +}; + + +} // namespace ecl + +#endif /* ECL_CONVERTERS_INTEGERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/string.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/string.hpp new file mode 100644 index 0000000..eb9d79b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/string.hpp @@ -0,0 +1,134 @@ +/** + * @file /include/ecl/converters/string.hpp + * + * @brief Type conversions to c++ strings. + * + * A variety of functors that do type conversion to c++ strings. These + * are convenient, but slow ( unlike the char* converters). + * + * It could probably use extensions for the other integral types. That would + * require making a decent base class and inheriting across all the + * integral types. + * + * @date April 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_STRINGS_HPP_ +#define ECL_CONVERTERS_STRINGS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "converter.hpp" +#include "char.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** String Converter Interface +*****************************************************************************/ +/** + * @brief Converts int to string, convenient but slow. + * + * Slightly slower but convenient (no need for preallocating buffers) + * conversion of int to a string. This + * implementation is based on a technique similarly used in the stlsoft + * libraries. + * + * @sa Converter + **/ +template <> +class Converter : public converters::ConverterBase { +public: + /** + * @brief Converts an integer into a string. + * + * This is slow in comparison to the + * buffered character string functions. There is no + * need for error handling here as it will always work. + * + * @param input : the integer to be converted. + * @return string : the string representation of the integer. + **/ + std::string operator ()(const int &input) + { + std::string s; + bool negative = false; + char *char_string; + #if ECL_SIZE_OF_INT == 4 + char_string = buffer + 11; + #elif ECL_SIZE_OF_INT == 8 + char_string = buffer + 20; + #else // just make sure we have lots of space + char_string = buffer + 30; + #endif + *char_string = '\0'; + int remaining = input; + unsigned int lsd; + /********************* + ** Fix sign + **********************/ + if (remaining < 0 ) { + negative = true; + remaining *= -1; + } + do + { + --char_string; + lsd = remaining%10; + remaining /= 10; + *char_string = Converter()(lsd); + } while ( remaining > 0); + if ( negative ) { + --char_string; + *char_string = '-'; + } + return s.assign(char_string); + }; + + virtual ~Converter() {} + +private: + #if ECL_SIZE_OF_INT == 4 + char buffer[12]; + #elif ECL_SIZE_OF_INT == 8 + char buffer[21]; + #else // just make sure we have lots of space + char buffer[31]; +#endif +}; + +/** + * @brief Convenient, but slow conversions to text format with strings. + * + * This groups all the string converters of fundamental types into a single + * cohesive superclass. At times, this is more convenient than using the + * string converters individually. + * + * @sa Converter + **/ +template <> +class Converter : + public Converter +{ +public: + virtual ~Converter() {} + + using Converter::operator(); +}; + + +} // namespace ecl + + +#endif /*ECL_CONVERTERS_STRINGS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/to_byte_array.hpp b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/to_byte_array.hpp new file mode 100644 index 0000000..3cc8c40 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/include/ecl/converters/to_byte_array.hpp @@ -0,0 +1,471 @@ +/** + * @file /include/ecl/converters/to_byte_array.hpp + * + * @brief Convert to byte arrays. + * + * @date March 2010 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_CONVERTERS_TO_BYTE_ARRAY_HPP_ +#define ECL_CONVERTERS_TO_BYTE_ARRAY_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "converter.hpp" +#include +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/** + * @cond DO_NOT_DOXYGEN + */ +namespace converters +{ + +/***************************************************************************** + ** Interface + *****************************************************************************/ + +/** + * @brief Integral to byte array converter. + * + * This class is not meant to be used directly, rather it is a + * simple base class for specialisations. This is kept separate because it + * the generic template type calls will clash with the default + * converter template specification. Specialise this for + * the various classes we actually want to use + * (i.e. see Converter> etc.) + */ +template +class IntegralToByteArray : public ConverterBase +{ +public: + /** + * @brief Convert from integral to byte array. + * + * This is a bit different to most converters as it takes in both arguments. The first argument is + * needed to supply the necessary byte array storage. We don't want to waste time + * copying the data out, and also we will sometimes want to overlay on part of an + * underlying buffer (via ecl_container stencils). + * + * The bytes are ordered from least significant to most + * significant (little-endian). + * + * Note this throws an exception and/or sets the converter error flag if the byte array + * storage does not match the requirements of the integral type to be converted. + * + * @param byte_array : the underlying array storage, it must match the integral type size. + * @param input : the integral to be converted. + * @return ByteArray& : convenience handle to the byte array. + * @exception : throws if the byte array storage size does not match the integral byte size [debug mode only]. + */ + const ByteArray& operator()(ByteArray &byte_array, const Integral &input) + { + /********************* + ** Checks + **********************/ + ecl_compile_time_concept_check(ecl::ContainerConcept); + ecl_compile_time_concept_check(ecl::ByteContainerConcept); + ecl_compile_time_assert(is_integral::value); + /********************* + ** Configuration + **********************/ + if (byte_array.size() != ecl::numeric_limits::bytes) + { + std::cout << "Failed size check [size: " << byte_array.size() << "][numeric_limits: "<< ecl::numeric_limits::bytes << "]" << std::endl; + error_handler = ConversionError; + ecl_debug_throw( + StandardException(LOC,ConversionError,"The specified byte array size does not match the byte size of the integral type.")); + return byte_array; + } + + /********************* + ** Method + **********************/ + for (unsigned int i = 0; i < ecl::numeric_limits::bytes; ++i) + { + byte_array[i] = static_cast(input >> 8 * i); +// Einstein was bit 'AND'ing a 0xff for dslam - is this useful? +// byte_array[i] = static_cast( input >> 8*i & 0xff); + } + return byte_array; + } + /** + * @brief Required virtual destructor. + */ + virtual ~IntegralToByteArray() {} +}; + +} // namespace converters +/** + * @endcond + */ + +/***************************************************************************** + ** Integral to Byte Array Converters + *****************************************************************************/ +/** + * @brief Converts int to a byte array of chars. + **/ +template<> +class Converter, int> : public converters::IntegralToByteArray, int> +{ +}; + +/** + * @brief Converts int to a byte array of unsigned chars. + **/ +template<> +class Converter, int> : public converters::IntegralToByteArray, + int> +{ +}; + +/** + * @brief Converts int to a byte array of signed chars. + **/ +template<> +class Converter, int> : public converters::IntegralToByteArray, int> +{ +}; + +/** + * @brief Converts unsigned int to a byte array of chars. + **/ +template<> +class Converter, unsigned int> : public converters::IntegralToByteArray, + unsigned int> +{ +}; + +/** + * @brief Converts unsigned int to a byte array of unsigned chars. + **/ +template<> +class Converter, unsigned int> : public converters::IntegralToByteArray< + std::vector, unsigned int> +{ +}; + +/** + * @brief Converts unsigned int to a byte array of signed chars. + **/ +template<> +class Converter, unsigned int> : public converters::IntegralToByteArray< + std::vector, unsigned int> +{ +}; + +/** + * @brief Converts long to a byte array of chars. + **/ +template<> +class Converter, long> : public converters::IntegralToByteArray, long> +{ +}; + +/** + * @brief Converts long to a byte array of unsigned chars. + **/ +template<> +class Converter, long> : public converters::IntegralToByteArray, + long> +{ +}; + +/** + * @brief Converts long to a byte array of signed chars. + **/ +template<> +class Converter, long> : public converters::IntegralToByteArray, long> +{ +}; + +/** + * @brief Converts unsigned long to a byte array of chars. + **/ +template<> +class Converter, unsigned long> : public converters::IntegralToByteArray, + unsigned long> +{ +}; + +/** + * @brief Converts unsigned long to a byte array of unsigned chars. + **/ +template<> +class Converter, unsigned long> : public converters::IntegralToByteArray< + std::vector, unsigned long> +{ +}; + +/** + * @brief Converts unsigned long to a byte array of signed chars. + **/ +template<> +class Converter, unsigned long> : public converters::IntegralToByteArray< + std::vector, unsigned long> +{ +}; + +/** + * @brief Converts long long to a byte array of chars. + **/ +template<> +class Converter, long long> : public converters::IntegralToByteArray, long long> +{ +}; + +/** + * @brief Converts long long to a byte array of unsigned chars. + **/ +template<> +class Converter, long long> : public converters::IntegralToByteArray, +long long> +{ +}; + +/** + * @brief Converts long long to a byte array of signed chars. + **/ +template<> +class Converter, long long> : public converters::IntegralToByteArray, long long> +{ +}; + +/***************************************************************************** + ** Byte Converter Interface + *****************************************************************************/ +/** + * @brief Converts a char string of human readable hexes to a byte array. + * + * Parses a string of hexes into a character byte array. + * + * @sa Converter + **/ +template<> +class Converter, char*> : public converters::ConverterBase +{ +public: + /** + * Converts a string of human readable hexes into a byte array. + * + * The string should contain bytes written as a '0x' followed + * by two hex digits. e.g. + * + * @code + * 0x32 0x64 0x64 0x54 + * @endcode + * + * This throws an exception and/or configures the error() + * function if an unexpected char is discovered. + * + * @param input : the character string to be converted. + * @return vector : the byte array. + * @exception StandardException : throws if unexpected char is discovered (debug mode only). + **/ + std::vector operator ()(const char* input) + { + + std::vector bytes; + state = waiting_zero; + + while (*input != '\0') + { + switch (state) + { + case (waiting_zero): + { + if (*input == '0') + { + state = waiting_x; + } + else if (*input == ' ') + { + // ignore whitespace + } + else + { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + bytes.clear(); + return bytes; + } + break; + } + case (waiting_x): + { + if (*input == 'x') + { + state = waiting_first_digit; + } + else + { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + bytes.clear(); + return bytes; + } + break; + } + case (waiting_first_digit): + { + if ((*input >= '0') && (*input <= '9')) + { + byte = (*input - '0') << 4; + state = waiting_second_digit; + } + else if ((*input >= 'a') && (*input <= 'f')) + { + byte = ((*input - 'a') + 0x0A) << 4; + state = waiting_second_digit; + } + else if ((*input >= 'A') && (*input <= 'F')) + { + byte = ((*input - 'A') + 0x0A) << 4; + state = waiting_second_digit; + } + else + { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + bytes.clear(); + return bytes; + } + break; + } + case (waiting_second_digit): + { + if ((*input >= '0') && (*input <= '9')) + { + byte += *input - '0'; + bytes.push_back(byte); + } + else if ((*input >= 'a') && (*input <= 'f')) + { + byte += (*input - 'a') + 0x0A; + bytes.push_back(byte); + } + else if ((*input >= 'A') && (*input <= 'F')) + { + byte += (*input - 'A') + 0x0A; + bytes.push_back(byte); + } + else + { + ecl_debug_throw(StandardException(LOC,ConversionError)); + error_handler = ConversionError; + bytes.clear(); + return bytes; + } + state = waiting_zero; + break; + } + default: + { + state = waiting_zero; + break; + } + } + ++input; + } + return bytes; + } + ; + virtual ~Converter() + { + } + +private: + unsigned int state; + char byte; + static const unsigned int waiting_zero = 0; + static const unsigned int waiting_x = 1; + static const unsigned int waiting_first_digit = 2; + static const unsigned int waiting_second_digit = 3; +}; + +/***************************************************************************** + * Byte Array Converter Family + ****************************************************************************/ +/** + * @brief Family of converters to byte arrays of vector type. + **/ +template<> +class Converter, void> : public Converter, char*>, public Converter< + std::vector, int>, + public Converter, unsigned int>, public Converter< + std::vector, long>, + public Converter, unsigned long> +{ +public: + virtual ~Converter() + { + } + + using Converter, char*>::operator(); + using Converter, int>::operator(); + using Converter, unsigned int>::operator(); + using Converter, long>::operator(); + using Converter, unsigned long>::operator(); +}; + +/** + * @brief Family of converters to byte arrays of vector type. + **/ +template<> +class Converter, void> : public Converter, int>, + public Converter, unsigned int>, + public Converter, long>, + public Converter, unsigned long> +{ +public: + virtual ~Converter() + { + } + + using Converter, int>::operator(); + using Converter, unsigned int>::operator(); + using Converter, long>::operator(); + using Converter, unsigned long>::operator(); +}; + +/** + * @brief Family of converters to byte arrays of vector type. + **/ +template<> +class Converter, void> : public Converter, int>, + public Converter, unsigned int>, + public Converter, long>, + public Converter, unsigned long> +{ +public: + virtual ~Converter() + { + } + + using Converter, int>::operator(); + using Converter, unsigned int>::operator(); + using Converter, long>::operator(); + using Converter, unsigned long>::operator(); +}; + +} // namespace ecl + +#endif /* ECL_CONVERTERS_TO_BYTE_ARRAY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_converters/mainpage.dox b/ros2_ws/src/ecl_core/ecl_converters/mainpage.dox new file mode 100644 index 0000000..7039563 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/mainpage.dox @@ -0,0 +1,248 @@ +/** +\mainpage +\htmlinclude manifest.html + + + @section Introduction + + The converters here provide a fast and type-safe means of doing + type conversion, but lack formatting capabilities. If you need + formatting capabilities with conversion to text types, use the + formatter classes provided in ecl_formatters. + + They're also used to provide generic conversions between + types (such as conversions between the various rotational + entities in the a robotics math module - quaternion, angle-axis + and rotation matrix). While these conversion functions can + just as easily be incorporated inside classes themselves, + having an external converter functor enables you to + decouple the interface and also add converter functionality + to fixed libraries incorporated within the ecl (such as + eigen). + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The error interfaces + using ecl::Converter; + @endcode + + Since it is a template class, no linking is required if you are only using this class. + + @section History + + Type conversions can be done in a variety of ways, all of which + require the user to pay some attention to the performance of the + converters. Some examples include: + + - sprintf : not type-safe but reasonably fast. + - stringstreams : type-safe but really slow. + - stlsoft shims : type-safe and very fast, but awkward to use. + + Sprintf is actually not that fast - it is burdened with formatting + functionalities, so if you do not need the formatting, it makes for + a poor type converter, especially given that it is also not type-safe. + + Stringstreams are so slow to the point of not being very useful at all + for control. + + Shims appear to be a very optimal, high-speed implementation, + especially on 8-32 bit systems. 64 bit compilers are still improving though + and as a consequence the shims' performance should improve there too. + However they are awkward to use and very little documentation on the + implementation that is setup by the guys who've heavily developed + stlsoft's implementation of these. + + @section ConvertersUsageSection Usage + + @subsection Instantiation + + Converters are functors - functions with state. You instantiate a converter type and + then make use of it as if it were a function call. + + @code + Converter floatToCharString; + Converter intToString; + @endcode + + For some types, it is possible to instantiate an object which incorporates all + of the currently convertable fundamental types together. This is sometimes convenient when + converting from many different types or if the converter requires a specific piece of + machinery. Character strings are the perfect example, as you will often wish to + convert from many different formats and because they require a buffer. If the + buffer is shared, it saves either expensive instantiations for each conversion type or + complicated buffer passing between the converters. + + @code + Converter toCharString; + Converter toString; + @endcode + + @subsection ConvertersTypeConversion Type Conversion Fallback + + If no specialisation exists, the primary converter template classes will + inspect the output type's class definition for a typedef'd converter (in a similar + fashion to iterators). + + @subsection ConvertersBufferedTypeConversion Buffered Type Conversion [char*] + + These are a really really fast means of doing conversions to a text + format, but they require particular care with buffering and ensuring + you do not read past arrays. The default implementation for character + strings abstracts this implementation behind a class wrapper. It will set + up a buffer and do the buffer manipulation behind the wrapper for you. + + The conversion algorithm for integral types is hand-specified, so it + avoids the formatting checks made by the other converters. I'd like to + do the same for the float types, but haven't managed to implement + this well yet, so it defaults back to c's sprintf function, which is + still as fast or faster than most other implementations. + + @code + Converter convertCharString; + char* charString; + int i = 255; + + charString = toCharString(i); + cout << charString << endl; + @endcode + + You might be curious where the character string buffer is stored in the above code. In this + case, the buffer is stored in the Converter object. As the character strings + are pointing to this buffer, you must ensure that the Converter hangs around long enough + to use the result. + + If you wish to reduce the footprint of the converter, you can also manually + instruct it to use a buffer of a certain size: + + @code + Converter toCharString(30); + @endcode + + Alternatively you can pass the converter an external buffer to use: + + @code + char buffer[30]; + Converter toCharString1(buffer,buffer+29); + + char *s1,*s2; + s1 = buffer+10; + s2 = buffer+20; + Converter toCharString1(s1,s2); + @endcode + + Float to char* converters are the one exception in this family, in that they do + have a small formatting capability, namely, the number of decimal places which + will get converted. + + @code + ecl::Converter converter; + std::cout << converter(2.134) << std::endl; // defaults to as large as needs be + std::cout << converter2(2.134,2) << std::endl; // prints only 2.13 + @endcode + + Note that if the precision causes the assigned buffer to be exceeded, the + converter will just lop off any extra decimal places of precision. + + @subsection ByteArrayConverters Byte Array Converters + + These convert to and from byte arrays (char arrays), which are very useful + in reading/writing to and from i/o devices. They'll typically work with + any container with the usual c++ style handles, though the obvious is for + std::vector containers: + + @code + typedef std::vector ByteArray; + Converter< ByteArray, ecl::int32 > toByteArray; + ByteArray byte_array(4); // ensure memory reserved matches integral type size + // these require a buffer for speed and practicality (aka char string converters) + toByteArray(byte_array, ecl::int32(363)); // converts to 0x6b 0x01 0x00 0x00 + toByteArray(byte_array, ecl::int32(-2)); // converts to 0xfe 0xff 0xff 0xff + Converter< int, ByteArray > fromByteArray; + int i = fromByteArray(byte_array); + std::cout << std::dec << "i: " << i << std::endl; + @endcode + + @section ConvertersSpeedSection Performance + + Of particular interest is the conversions from a number type to character + string as these are used to build up the formatters for use with ecl_streams. + There is a benchmarking program for string conversions in the ecl_core_apps package. + + In general, the converters outperform sprintf and iostream (simply because + no formatting checks are made in most cases), in some cases they outperform + these considerably. The only case which is missing is that of an optimised + algorithm for float to char string conversions - it just falls back to + sprintf for now. + + @section ConverterWriting Writing Your Own Converters + + It is impossible to add to the converter families, but it is simple + to add specialisations for individual conversions. A typical + specialisation would have the following code structure, + @code + namespace ecl { + + template <> + class Converter { + public: + inline Matrix operator()(Vector &input) { + // implementation + return Matrix(M); + } + }; + }; // namespace ecl + @endcode + Usage would be as follows, + @code + Converter toMatrix; + Converter toString; + + string s; + Matrix m; + Vector v; + m = toMatrix(v); + s = toString(m); + @endcode + + Another alternative is to make use of the default parent template structure, + which, in the absence of a specialisation will look in the input type's + class definition for a typedef'd Converter. + + The above example is a little contrived as the same effect could be achieved + with member functions in the matrix and vector classes. Shims really become + useful only when they requires some additional internal structure such as is + the case for character string converters - these require initialisation and + continued maintenance of an internal buffer. + + @section ConverterList Current List of Fundamental Converters + + The following are listed with the 'to' type on the left and 'from' types on the right. + + - char : uint + - string : int + - char* : all integer/float types + - int : char, char*, string + - char* : byte array (i.e. byte array to hex string converter) + - byte array : char* (i.e. hex string to byte array converter) + +\section unitTests Unit Tests + + - src/test/converters.cpp + - src/test/byte_array_converters.cpp + +\section utilities Utilities + + - ecl_core_apps/src/benchmarks/string_conversions.cpp : benchmarks the speed of char string conversions. + +\section ChangeLog + + - Feb 11 : moved out from ecl_utilities. + + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_converters/package.xml b/ros2_ws/src/ecl_core/ecl_converters/package.xml new file mode 100644 index 0000000..4bb932b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/package.xml @@ -0,0 +1,47 @@ + + + ecl_converters + 1.2.1 + + Some fast/convenient type converters, mostly for char strings or strings. + These are not really fully fleshed out, alot of them could use the addition for + the whole range of fundamental types (e.g. all integers, not just int, unsigned int). + + They will come as the need arises. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_converters + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_mpl + ecl_type_traits + ecl_concepts + + ecl_license + ecl_concepts + ecl_config + ecl_errors + ecl_exceptions + ecl_mpl + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/src/CMakeLists.txt new file mode 100644 index 0000000..6496acf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(examples) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/src/examples/CMakeLists.txt new file mode 100644 index 0000000..a5fed17 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/examples/CMakeLists.txt @@ -0,0 +1,9 @@ +############################################################################## +# Files +############################################################################## + +add_executable(demo_float_converters float_converters.cpp) +target_link_libraries(demo_float_converters + ${PROJECT_NAME} +) +install(TARGETS demo_float_converters RUNTIME DESTINATION lib/${PROJECT_NAME}) diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/examples/float_converters.cpp b/ros2_ws/src/ecl_core/ecl_converters/src/examples/float_converters.cpp new file mode 100644 index 0000000..c2b82cf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/examples/float_converters.cpp @@ -0,0 +1,65 @@ +/** + * @file /ecl_converters/src/examples/float_converters.cpp + * + * @brief Demo for the float style precision converters + * + * @date March 2011 + **/ + +#include +#include "../../include/ecl/converters/char_strings.hpp" + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Preassigned Buffer" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + char buf[4]; + ecl::Converter converter(buf, buf+4); + std::cout << "converter(2.134): " << converter(2.134) << std::endl; + std::cout << "converter(2.134,2): " << converter(2.134,2) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Internal Default Buffer" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "The default internal buffer is size 250, but lets set 125." << std::endl; + ecl::Converter converter2(125); + std::cout << "converter(2.134): " << converter2(2.134) << std::endl; + std::cout << "converter(2.134,2): " << converter2(2.134,2) << std::endl; + ecl::Converter converter3; + std::cout << "converter(2.134): " << converter3(2.134) << std::endl; + std::cout << "converter(2.134,2): " << converter3(2.134,2) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Playing with strings" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::string s0(converter2(2.134,2)); + std::string s1 = converter2(2.134,2); + std::cout << "String creation: " << s0 << std::endl; + std::cout << "String creation: " << s1 << std::endl; + + ecl::Converter int_converter; + std::cout << int_converter(3) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + return 0; +} + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_converters/src/test/CMakeLists.txt new file mode 100644 index 0000000..51e6d42 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/test/CMakeLists.txt @@ -0,0 +1,20 @@ +############################################################################### +# Google Tests Macro +############################################################################### + +macro(ecl_converters_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} + ${PROJECT_NAME} + ecl_config::ecl_config + ) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_converters_add_gtest(byte_array_converters) +ecl_converters_add_gtest(converters) diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/test/byte_array_converters.cpp b/ros2_ws/src/ecl_core/ecl_converters/src/test/byte_array_converters.cpp new file mode 100644 index 0000000..dc0c7e4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/test/byte_array_converters.cpp @@ -0,0 +1,155 @@ +/** + * @file /src/test/byte_array_converters.cpp + * + * @brief Unit test for the byte array converters. + * + * @date August 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/converters/to_byte_array.hpp" +#include "../../include/ecl/converters/from_byte_array.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Converter; + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +typedef std::vector ByteArray; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +bool debug_output = false; + +void print(const ByteArray &byte_array) { + if( debug_output ) { + for ( unsigned int i = 0; i < byte_array.size(); ++i ) { + std::cout << "0x" << std::hex << static_cast(byte_array[i]) << " "; + } + std::cout << std::endl; + } +} + +void print(const std::vector &byte_array) { + if( debug_output ) { + for ( unsigned int i = 0; i < byte_array.size(); ++i ) { + std::cout << "0x" << std::hex << static_cast(byte_array[i]) << " "; + } + std::cout << std::endl; + } +} +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Converter,fromByteArray) { + ByteArray byte_array; + byte_array.push_back(0x01); + byte_array.push_back(0x02); + byte_array.push_back(0x03); + Converter converter; +// std::cout << "Byte Array Conversion : " << converter(byte_array) << std::endl; + EXPECT_EQ(197121,converter(byte_array)); +} + +TEST(Converter,toByteArray) { + ecl::Converter< ByteArray, int > toByteArray; + ByteArray byte_array(4,0x00); + toByteArray(byte_array, 363); + print(byte_array); + EXPECT_EQ(107,byte_array[0]); + toByteArray(byte_array,-2); + print(byte_array); + EXPECT_EQ(254,byte_array[0]); + ecl::Converter< int, ByteArray > fromByteArray; + int i = fromByteArray(byte_array); + if ( debug_output ) { + std::cout << std::dec << "i: " << i << std::endl; + } + EXPECT_EQ(-2,i); + toByteArray(byte_array, 258); + print(byte_array); + i = fromByteArray(byte_array); + if ( debug_output ) { + std::cout << std::dec << "i: " << i << std::endl; + } +} +TEST(Converter,toByteArrayFailedSize) { + #if defined(NDEBUG) || defined(ECL_NDEBUG) + std::cout << "Skipping toByteArrayFailedSize test, it only throws in debug mode" << std::endl; + SUCCEED(); + #else + ecl::Converter< ByteArray, ecl::int32 > toByteArray; + ecl::int32 i = 363; + ByteArray byte_array; + try { + byte_array = toByteArray(byte_array, i); + } catch ( ecl::StandardException &e ) { + if ( debug_output ) { std::cout << "Caught an exception from improper size of reserved memory." << std::endl; } + } + ecl::Error result = toByteArray.error(); + if ( result.flag() == ecl::ConversionError ) { + SUCCEED(); + } else { + std::cout << "Result Flag: " << result.flag() << std::endl; + std::cout << "ConversionError: " << ecl::ConversionError << std::endl; + FAIL(); + } + #endif +} + +TEST(Converter,charToByteArray) { + Converter< std::vector > toCharByteArray; + std::vector bytes = toCharByteArray("0x32 0x54"); + if(debug_output) { + print(bytes); + } + EXPECT_EQ(50,bytes[0]); + EXPECT_EQ(84,bytes[1]); + std::vector bytes_258(4,0x00); + toCharByteArray(bytes_258, ecl::int32(258)); + print(bytes_258); + ecl::Converter< ecl::int32, std::vector > fromCharByteArray; + ecl::int32 i = fromCharByteArray(bytes_258); + if ( debug_output ) { + std::cout << std::dec << "i: " << i << std::endl; + } +} + +TEST(Converter,byteArrayStringConverters) { + std::string str("dude"); + ecl::converters::FromByteArray from_byte_array; + int i = from_byte_array(str); + if ( debug_output ) { + std::cout << "i: " << i << std::endl; + } + // is this correct? I haven't actually verified this. + EXPECT_EQ(1701082468,i); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + + diff --git a/ros2_ws/src/ecl_core/ecl_converters/src/test/converters.cpp b/ros2_ws/src/ecl_core/ecl_converters/src/test/converters.cpp new file mode 100644 index 0000000..48dae14 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_converters/src/test/converters.cpp @@ -0,0 +1,127 @@ +/** + * @file /src/test/converters.cpp + * + * @brief Unit Test for @ref ecl::Converter "Converter". + * + * @date April 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/converters/to_byte_array.hpp" +#include "../../include/ecl/converters/char.hpp" +#include "../../include/ecl/converters/char_strings.hpp" +#include "../../include/ecl/converters/string.hpp" +#include "../../include/ecl/converters/integers.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::Converter; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +const bool debug_output = true; +//const bool debug_output = false; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Converter,toChar) { + Converter uintToAscii; + Converter intToAscii; + Converter toAscii; + + if(debug_output) { + std::cout << "uintToAscii(8U): " << uintToAscii(8U) << std::endl; + std::cout << "intToAscii(8): " << intToAscii(8) << std::endl; + std::cout << "toAscii(8): " << toAscii(8) << std::endl; + std::cout << "toAscii(8U): " << toAscii(8U) << std::endl; + } + + EXPECT_EQ('8',uintToAscii(8U)); + EXPECT_EQ('8',intToAscii(8)); + EXPECT_EQ('8',toAscii(8U)); + EXPECT_EQ('8',toAscii(8)); +} + +TEST(Converter,toString) { + Converter intToString; + if(debug_output) { + std::cout << "intToString(123): " << intToString(123) << std::endl; + std::cout << "intToString(-123): " << intToString(-123) << std::endl; + } + EXPECT_EQ(string("123"),intToString(123)); + EXPECT_EQ(string("-123"),intToString(-123)); +} + +TEST(Converter,toInt) { + Converter toInt; + if(debug_output) { + std::cout << "toInt:" << std::endl; + std::cout << " string -> " << toInt(string("123")) << std::endl; +// std::cout << " char* -> " << toInt("-123") << std::endl; + std::cout << " char -> " << toInt('3') << std::endl; + } + EXPECT_EQ(123,toInt(string("123"))); +// EXPECT_EQ(-123,toInt("-123")); // fix this once i have the proper byte array converter in. + EXPECT_EQ(3,toInt(char('3'))); +} + +TEST(Converter,toCharString) { + // Bit hard to test these. + Converter toCharString; + char c = 'A'; + unsigned char uc = 'A'; + short s = -111; + unsigned short us = 111; + int i = -111; + unsigned int ui = 111; + long l = -111; + unsigned long ul = 111; + long long ll = -111111; + unsigned long long ull = 11111111; + float f = -321.23; + double d = -321.23; + char buffer[44]; + Converter floatToCharString(buffer, buffer+4); + + if(debug_output) { + std::cout << "toCharString:" << std::endl; + std::cout << " char -> " << toCharString(c) << std::endl; + std::cout << " unsigned char -> " << toCharString(uc) << std::endl; + std::cout << " short -> " << toCharString(s) << std::endl; + std::cout << " unsigned short-> " << toCharString(us) << std::endl; + std::cout << " int -> " << toCharString(i) << std::endl; + std::cout << " unsigned int -> " << toCharString(ui) << std::endl; + std::cout << " long -> " << toCharString(l) << std::endl; + std::cout << " unsigned long -> " << toCharString(ul) << std::endl; + std::cout << " long long -> " << toCharString(ll) << std::endl; + std::cout << " unsigned llong-> " << toCharString(ull) << std::endl; + std::cout << " float -> " << toCharString(f) << std::endl; + std::cout << " double -> " << toCharString(d) << std::endl; + std::cout << " float(2) -> " << toCharString(f,2) << std::endl; + std::cout << " double(2) -> " << toCharString(d,2) << std::endl; + std::cout << " float (w/ buf)-> " << floatToCharString(f) << std::endl; + } + SUCCEED(); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_core/.cproject b/ros2_ws/src/ecl_core/ecl_core/.cproject new file mode 100644 index 0000000..c3ddb85 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core/.cproject @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_core/.project b/ros2_ws/src/ecl_core/ecl_core/.project new file mode 100644 index 0000000..2595391 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core/.project @@ -0,0 +1,83 @@ + + + ecl_core + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + -j4 + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_core/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_core/CHANGELOG.rst new file mode 100644 index 0000000..2e66136 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core/CHANGELOG.rst @@ -0,0 +1,73 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +1.0.1 (2018-12-31) +------------------ +* metapackage tag dropped + +0.60.5 (2013-07-05) +------------------- + +* Bugfixes for catkin library finding in raring. + +0.60.2 (2013-07-02) +------------------- + +* Bugfixes to windows port. + +0.60.0 (2013-06-28) +------------------- + +* Windows port +* First **hydro** release. + +0.50.5 (2013-02-15) +------------------- + +0.50.4 (2013-02-15) +------------------- + +* Bugfixes for catkin. + +0.50.3 (2012-12-22) +------------------- + +* Bugfixes for quantal's gcc. +* Parallel build directory header generation. + +0.50.2 (2012-12-15) +------------------- + +* Catkin upgrade fixes. + +0.50.1 (2012-12-01) +------------------- + +* Bugfixes for ecl in release mode builds. + +0.50.0 (2012-10-30) +------------------- + +* Upgraded for catkin. +* First **groovy** release. + +0.43.9 (2012-05-24) +------------------- + +* Upgraded with bugfixes for fuerte and precise. +* First **fuerte** release. + +0.43.8 (2012-04-17) +------------------- + +* Upgraded eigen and dependant modules. + +0.43.6 (2012-01-13) +------------------- + +* Initial stack import into ros. +* First **electric** release. + + + diff --git a/ros2_ws/src/ecl_core/ecl_core/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_core/CMakeLists.txt new file mode 100644 index 0000000..ec7fd3b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.5) +project(ecl_core) +find_package(ament_cmake_ros REQUIRED) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_core/package.xml b/ros2_ws/src/ecl_core/ecl_core/package.xml new file mode 100644 index 0000000..9260cd8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core/package.xml @@ -0,0 +1,44 @@ + + + ecl_core + 1.2.1 + + A set of tools and interfaces extending the capabilities of c++ to + provide a lightweight, consistent interface with a focus for control + programming. + + Daniel Stonier + BSD-3-Clause + http://www.ros.org/wiki/ecl_core + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier + + ament_cmake_ros + + ecl_command_line + ecl_concepts + ecl_containers + ecl_converters + ecl_core_apps + ecl_devices + ecl_eigen + ecl_exceptions + ecl_formatters + ecl_geometry + ecl_ipc + ecl_linear_algebra + ecl_math + ecl_mpl + ecl_sigslots + ecl_statistics + ecl_streams + ecl_threads + ecl_time + ecl_type_traits + ecl_utilities + + + ament_cmake + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/.cproject b/ros2_ws/src/ecl_core/ecl_core_apps/.cproject new file mode 100644 index 0000000..ef0107b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/.cproject @@ -0,0 +1,474 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + + true + + true + + true + + + + + + make + + + + all + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/.project b/ros2_ws/src/ecl_core/ecl_core_apps/.project new file mode 100644 index 0000000..fcad33f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/.project @@ -0,0 +1,78 @@ + + + ecl_core_apps + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_core_apps/CHANGELOG.rst new file mode 100644 index 0000000..fc4d490 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/CHANGELOG.rst @@ -0,0 +1,16 @@ +========= +Changelog +========= + +0.61.9 (2016-02-23) +------------------- +* improved output of the quatnerion-yaw utilities + +0.61.1 (2015-07-22) +------------------- +* quaternion2yaw utility + +0.61.0 (2014-09-12) +------------------- +* yaw2quaternion converter. + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_core_apps/CMakeLists.txt new file mode 100644 index 0000000..2428cc2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/CMakeLists.txt @@ -0,0 +1,56 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_core_apps) + +############################################################################## +# ament +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_linear_algebra REQUIRED) +find_package(ecl_command_line REQUIRED) +find_package(ecl_converters REQUIRED) +find_package(ecl_containers REQUIRED) +find_package(ecl_devices REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_geometry REQUIRED) +find_package(ecl_ipc REQUIRED) +find_package(ecl_sigslots REQUIRED) +find_package(ecl_streams REQUIRED) +find_package(ecl_threads REQUIRED) +find_package(ecl_type_traits REQUIRED) +find_package(ecl_time_lite REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/mainpage.dox new file mode 100644 index 0000000..35017c5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/mainpage.dox @@ -0,0 +1,38 @@ +/** +\mainpage +\htmlinclude manifest.html + +@section packageSummary Package Summary + +This package collects some useful utility programs developed within the ecl_core +framework. These programs have many different dependencies that otherwise couldn't +be installed with their respective package, so are collected here. + +\section Benchmarks + +- src/benchmarks/exceptions.cpp : evaluates exception handling costs on your system. +- src/benchmarks/files.cpp : tests the raw read/write speed of various file mechanisms. +- src/benchmarks/flops.cpp : the classic flops test. +- src/benchmarks/snooze.cpp : determines the latency of your absolute timer. +- src/benchmarks/streams.cpp : compares various streaming mechanisms. +- src/benchmarks/string_conversions.cpp : benchmarks various string converting utilities. + +\section Utilities + +- src/utils/hex.cpp : utility for testing serial devices with raw hex data. +- src/utils/serial.cpp : a generic serial connection testing program. +- src/utils/process.cpp : detects various process statistics. + +\section ChangeLog + +- May 11 : Moved what I could back to their own packages. +- Apr 10 : The famous flops benchmark test. +- Jan 09 : Simple socket client-server interface for posix. +- Dec 09 : Comparison test for various streaming mechanisms. +- Dec 09 : The serial utilities, hex and serial. +- Dec 09 : Latency benchmark for periodic timers working on absolute times. +- Oct 09 : Comparison test for various file io api. +- Sep 09 : A benchmark test for timing the cost of exceptions. +- May 09 : Comparison test for the various container types. +- May 09 : Comparison test for the c/c++/ecl api doing char string conversions. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/namespaces.dox new file mode 100644 index 0000000..28afb51 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/doxygen/namespaces.dox @@ -0,0 +1,29 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::benchmarks + * + * @brief Benchmark tests. + * + * These programs benchmark useful features in the ecl, eigen and the embedded platform. + **/ +/** + * @namespace ecl::demos + * + * @brief Demo programs. + * + * These programs demo usage of various ecl modules/classes. + **/ +/** + * @namespace ecl::utils + * + * @brief Utility programs. + * + * Programs that are useful as tools for devleping on embedded systems. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/package.xml b/ros2_ws/src/ecl_core/ecl_core_apps/package.xml new file mode 100644 index 0000000..7940f86 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/package.xml @@ -0,0 +1,61 @@ + + + ecl_core_apps + 1.2.1 + + This includes a suite of programs demo'ing various aspects of the + ecl_core. It also includes various benchmarking and utility programs for + use primarily with embedded systems. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_core_apps + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_build + ecl_license + ecl_config + ecl_linear_algebra + ecl_command_line + ecl_converters + ecl_containers + ecl_devices + ecl_errors + ecl_exceptions + ecl_formatters + ecl_geometry + ecl_ipc + ecl_sigslots + ecl_streams + ecl_threads + ecl_type_traits + ecl_time_lite + + ecl_build + ecl_license + ecl_config + ecl_linear_algebra + ecl_command_line + ecl_converters + ecl_containers + ecl_devices + ecl_errors + ecl_exceptions + ecl_formatters + ecl_geometry + ecl_ipc + ecl_sigslots + ecl_streams + ecl_threads + ecl_type_traits + ecl_time_lite + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_core_apps/src/CMakeLists.txt new file mode 100644 index 0000000..b9d7f93 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(benchmarks) +add_subdirectory(utils) diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/CMakeLists.txt new file mode 100644 index 0000000..3c19a67 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/CMakeLists.txt @@ -0,0 +1,46 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_add_benchmark name) + add_executable(ecl_bench_${name} ${name}.cpp) + target_link_libraries( + ecl_bench_${name} + PRIVATE + ecl_config::ecl_config + ecl_command_line::ecl_command_line + ecl_converters::ecl_converters + ecl_containers::ecl_containers + ecl_devices::ecl_devices + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_ipc::ecl_ipc + ecl_linear_algebra::ecl_linear_algebra + ecl_sigslots::ecl_sigslots + ecl_streams::ecl_streams + ecl_threads::ecl_threads + ecl_time_lite::ecl_time_lite + ecl_type_traits::ecl_type_traits + ) + install(TARGETS ecl_bench_${name} RUNTIME DESTINATION bin) +endmacro() + +############################################################################### +# Setup +############################################################################### + +ecl_add_benchmark(containers) +ecl_add_benchmark(files) +ecl_add_benchmark(flops) +ecl_add_benchmark(exceptions) +ecl_add_benchmark(snooze) +ecl_add_benchmark(streams) +ecl_add_benchmark(string_conversions) + +# Sparse is still unstable...and got modified in quantal, comment out for now. +#ecl_add_benchmark(eigen_sparse) +ecl_add_benchmark(eigen3_inverse) +ecl_add_benchmark(eigen3_decompositions) +ecl_add_benchmark(eigen3_transforms) diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/containers.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/containers.cpp new file mode 100644 index 0000000..568c350 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/containers.cpp @@ -0,0 +1,154 @@ +/** + * @file /src/benchmarks/containers.cpp + * + * @brief Benchmarks the performance of various container types. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using std::vector; +using ecl::Array; +using ecl::RealTimePriority4; +using ecl::StandardException; +using ecl::StopWatch; +using ecl::TimeStamp; + +/***************************************************************************** +** Main +*****************************************************************************/ + + +int main() +{ + try { + ecl::set_priority(RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + StopWatch stopwatch; + TimeStamp timestamp[5]; + + Array array_tmp; + array_tmp << 3,4,6,3; + array_tmp << 3,4,6,3; + array_tmp << 3,4,6,3; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructors" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + stopwatch.restart(); + // Array [manual] + Array array1; + for ( int i = 0; i < 4; ++i ) { + array1[i] = 3; + } + timestamp[0] = stopwatch.split(); + + // Array [comma] + Array array2; + array2 << 3,3,3,3; + timestamp[1] = stopwatch.split(); + + // Array [blueprint] + Array array3 = Array::Constant(3); + timestamp[2] = stopwatch.split(); + + // Vector [manual] + vector v1(4); + for ( int i = 0; i < 4; ++i ) { + v1[i] = 3; + } + timestamp[3] = stopwatch.split(); + + // Vector [manual] + int a1[4]; + for ( int i = 0; i < 4; ++i ) { + a1[i] = 3; + } + timestamp[4] = stopwatch.split(); + + std::cout << "carray [manual] : " << timestamp[4] << std::endl; + std::cout << "Array [blueprint]: " << timestamp[2] << std::endl; + std::cout << "Array [manual] : " << timestamp[0] << std::endl; + std::cout << "Array [comma] : " << timestamp[1] << std::endl; + std::cout << "Vector [manual] : " << timestamp[3] << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Accessors" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + int elements[4]; + + stopwatch.restart(); + for (int i = 0; i < 4; ++i ) { elements[i] = array1[i]; } + timestamp[0] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { elements[i] = array1.at(i); } + timestamp[1] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { elements[i] = v1[i]; } + timestamp[2] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { elements[i] = v1.at(i); } + timestamp[3] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { elements[i] = a1[i]; } + timestamp[4] = stopwatch.split(); + + (void)elements; + + std::cout << "carray [] : " << timestamp[4] << std::endl; + std::cout << "Array [] : " << timestamp[0] << std::endl; + std::cout << "Array at : " << timestamp[1] << std::endl; + std::cout << "Vector [] : " << timestamp[2] << std::endl; + std::cout << "Vector at : " << timestamp[3] << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Setters" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + stopwatch.restart(); + for (int i = 0; i < 4; ++i ) { array1[i] = 3; } + timestamp[0] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { array1 = Array::Constant(3); } + timestamp[1] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { v1[i] = 3; } + timestamp[2] = stopwatch.split(); + + for (int i = 0; i < 4; ++i ) { a1[i] = 3; } + timestamp[3] = stopwatch.split(); + + std::cout << "carray [manual] : " << timestamp[3] << std::endl; + std::cout << "Array [blueprint]: " << timestamp[1] << std::endl; + std::cout << "Array [manual] : " << timestamp[0] << std::endl; + std::cout << "Vector [manual] : " << timestamp[2] << std::endl; + +return 0; +} + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_decompositions.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_decompositions.cpp new file mode 100644 index 0000000..59836cc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_decompositions.cpp @@ -0,0 +1,200 @@ +/** + * @file /ecl_core_apps/src/benchmarks/eigen3_decompositions.cpp + * + * @brief Benchmark the decompositions in Eigen. + * + * @date 05/08/2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::StopWatch; +using ecl::TimeStamp; +using Eigen::Matrix3f; +using Eigen::MatrixXf; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + const unsigned int repeats = 5; + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + StopWatch stopwatch; + TimeStamp times[14]; + + MatrixXf A = MatrixXf::Random(100,100); + MatrixXf b = MatrixXf::Identity(100,100); + MatrixXf x(100,1); + + // get rid of caching effects. + for ( unsigned int i = 0; i < repeats; ++i ) { + x = A.colPivHouseholderQr().solve(b); + } + + times[0].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.colPivHouseholderQr().solve(b); + times[0] += stopwatch.split(); + } + times[1].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.fullPivHouseholderQr().solve(b); + times[1] += stopwatch.split(); + } + times[2].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.partialPivLu().solve(b); + times[2] += stopwatch.split(); + } + times[3].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.fullPivLu().solve(b); + times[3] += stopwatch.split(); + } + + ecl::Format format(15,9,ecl::RightAlign); + std::cout << std::endl; + std::cout << "************** Eigen3 Decompositions ***************" << std::endl; + std::cout << std::endl; + std::cout << "Ax=b where A = Rand(100,100) and b = Identity(100x100)" << std::endl; + std::cout << "i.e. solving the inverse (results averaged over " << repeats << " runs)" << std::endl; + std::cout << std::endl; + std::cout << "ColPivHouseHolder : " << format(static_cast(times[0])/static_cast(repeats)) << std::endl; + std::cout << "FullPivHouseHolder : " << format(static_cast(times[1])/static_cast(repeats)) << std::endl; + std::cout << "PartialPivLu : " << format(static_cast(times[2])/static_cast(repeats)) << std::endl; + std::cout << "FullPivLu : " << format(static_cast(times[3])/static_cast(repeats)) << std::endl; + std::cout << std::endl; + + b = MatrixXf::Random(100,1); + times[4].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.colPivHouseholderQr().solve(b); + times[4] += stopwatch.split(); + } + times[5].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.fullPivHouseholderQr().solve(b); + times[5] += stopwatch.split(); + } + times[6].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.partialPivLu().solve(b); + times[6] += stopwatch.split(); + } + times[7].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + A = MatrixXf::Random(100,100); + stopwatch.restart(); + x = A.fullPivLu().solve(b); + times[7] += stopwatch.split(); + } + + std::cout << "Ax=b where A = Rand(100,100) and b = Random(100x1)" << std::endl; + std::cout << "i.e. solving linear equations (results averaged over " << repeats << " runs)" << std::endl; + std::cout << std::endl; + std::cout << "ColPivHouseHolder : " << format(static_cast(times[4])/static_cast(repeats)) << std::endl; + std::cout << "FullPivHouseHolder : " << format(static_cast(times[5])/static_cast(repeats)) << std::endl; + std::cout << "PartialPivLu : " << format(static_cast(times[6])/static_cast(repeats)) << std::endl; + std::cout << "FullPivLu : " << format(static_cast(times[7])/static_cast(repeats)) << std::endl; + std::cout << std::endl; + + b = MatrixXf::Identity(100,100); + times[8].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.colPivHouseholderQr().solve(b); + times[8] += stopwatch.split(); + } + times[9].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.fullPivHouseholderQr().solve(b); + times[9] += stopwatch.split(); + } + times[10].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.partialPivLu().solve(b); + times[10] += stopwatch.split(); + } + times[11].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.fullPivLu().solve(b); + times[11] += stopwatch.split(); + } + times[12].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.llt().solve(b); +// A.llt().solveInPlace(b); // only marginally faster + times[12] += stopwatch.split(); + } + times[13].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + MatrixXf D = MatrixXf::Random(100,100); // This is actually a bit dangerous + A = D.transpose()*D; // because this will only be positive definite if D is invertible + stopwatch.restart(); + x = A.ldlt().solve(b); +// A.ldlt().solveInPlace(b); // only marginally faster + times[13] += stopwatch.split(); + } + + std::cout << "Ax=b where A = RandPosDef(100,100) and b = Identity(100x100)" << std::endl; + std::cout << "(results averaged over " << repeats << " runs)" << std::endl; + std::cout << std::endl; + std::cout << "ColPivHouseHolder : " << format(static_cast(times[8])/static_cast(repeats)) << std::endl; + std::cout << "FullPivHouseHolder : " << format(static_cast(times[9])/static_cast(repeats)) << std::endl; + std::cout << "PartialPivLu : " << format(static_cast(times[10])/static_cast(repeats)) << std::endl; + std::cout << "FullPivLu : " << format(static_cast(times[11])/static_cast(repeats)) << std::endl; + std::cout << "llt : " << format(static_cast(times[12])/static_cast(repeats)) << std::endl; + std::cout << "ldlt : " << format(static_cast(times[13])/static_cast(repeats)) << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_inverse.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_inverse.cpp new file mode 100644 index 0000000..cddd155 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_inverse.cpp @@ -0,0 +1,88 @@ +/** + * @file /ecl_core_apps/src/benchmarks/eigen3_inverse.cpp + * + * @brief Tests eigen3 inverses and decompositions. + * + * @date Aug 4, 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::StopWatch; +using ecl::TimeStamp; +using Eigen::Matrix3f; +using Eigen::MatrixXf; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + const unsigned int repeats = 10; + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + StopWatch stopwatch; + TimeStamp times[9]; + + Matrix3f M3 = Matrix3f::Random(); + Matrix3f M3I; + MatrixXf M100 = MatrixXf::Random(100,100); + MatrixXf M100I; + + // get rid of caching effects. + for ( unsigned int i = 0; i < repeats; ++i ) { + M3.inverse(); + } + + times[0].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + M3 = Matrix3f::Random(); + stopwatch.restart(); + M3I = M3.inverse(); + times[0] += stopwatch.split(); + } + times[1].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + M100 = MatrixXf::Random(100,100); + stopwatch.restart(); + M100I = M100.inverse(); + times[1] += stopwatch.split(); + } + times[2].stamp(0,0); + for ( unsigned int i = 0; i < repeats; ++i ) { + M100 = MatrixXf::Random(100,100); + stopwatch.restart(); + M100I = M100.fullPivLu().inverse(); + times[2] += stopwatch.split(); + } + + ecl::Format format(15,9,ecl::RightAlign); + std::cout << std::endl; + std::cout << "************** Eigen3 Inverse ***************" << std::endl; + std::cout << std::endl; + std::cout << " 3x3 (direct by val) : " << format(static_cast(times[0])/static_cast(repeats)) << std::endl; + std::cout << " 100x100 (PPivLU by val) : " << format(static_cast(times[1])/static_cast(repeats)) << std::endl; + std::cout << " 100x100 (FPivLU by val) : " << format(static_cast(times[2])/static_cast(repeats)) << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_transforms.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_transforms.cpp new file mode 100644 index 0000000..2ceb4b3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen3_transforms.cpp @@ -0,0 +1,412 @@ +/** + * @file /ecl_core_apps/src/benchmarks/eigen3_transforms.cpp + * + * @brief Benchmark various aspects of eigen's geometry module. + * + * @date September 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl; +using namespace Eigen; +using std::vector; + +/***************************************************************************** +** Pose2D +*****************************************************************************/ + +class NewPose2D { +public: + NewPose2D(){} + NewPose2D(const double &x, const double &y, const double& theta) : + rotation(Rotation2D(theta).toRotationMatrix()) + { + translation << x, y; + } + NewPose2D operator*(const NewPose2D& pose) const { + NewPose2D new_pose; + new_pose.translation = translation+rotation*pose.translation; + new_pose.rotation = rotation*pose.rotation; + return new_pose; + } + NewPose2D inverse() const { + NewPose2D p; + p.translation = rotation*translation; + p.rotation = -1*rotation; + return p; + } + void print() { + Rotation2D angle(0.0); + angle.fromRotationMatrix(rotation); + std::cout << "[ " << translation[0] << "," << translation[1] << "," << angle.angle() << "]" << std::endl; + } + + Matrix2d rotation; + Vector2d translation; +}; + +class Pose2D { +public: + Pose2D(const double &x_=0.0, const double &y_=0.0, const double&theta=0.0) : + x(x_), y(y_), rotation(theta) + {} + Pose2D(const Pose2D& pose) : x(pose.x), y(pose.y), rotation(pose.rotation) {} + + void operator=( const Pose2D& pose) { + x = pose.x; + y = pose.y; + rotation = pose.rotation; + } + + Pose2D inverse() const { + double s = sin(rotation); + double c = cos(rotation); + return Pose2D(c*x-s*y, s*x+c*y, -rotation); + } + + Pose2D operator*(const Pose2D& pose) const { + double s = sin(rotation); + double c = cos(rotation); + Pose2D new_pose(x+c*pose.x-s*pose.y, + y+s*pose.x + c*pose.y, + rotation+pose.rotation); + while (new_pose.rotation > +3.14) { new_pose.rotation -= 2*3.14; } + while (new_pose.rotation < -3.14) { new_pose.rotation += 2*3.14; } + return new_pose; + } + + void print() { + std::cout << "[ " << x << "," << y << "," << rotation << "]" << std::endl; + } + double x, y; + double rotation; +}; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +const unsigned int REPEAT = 1000; +const double increment = 1.0/static_cast(REPEAT); + +double random_float() { + return static_cast(rand()%99)/100.0; +} + +Matrix3d rotation3D(const double &alpha, const double &beta, const double &gamma) { + Matrix3d Ralpha, Rbeta, Rgamma; + Ralpha << 1.0, 0.0, 0.0, + 0.0, cos(alpha), -sin(alpha), + 0.0, sin(alpha), cos(alpha); + Rbeta << cos(beta), 0.0, sin(beta), + 0.0, 1.0, 0.0, + -sin(beta), 0.0, cos(beta); + Rgamma << cos(gamma), -sin(gamma), 0.0, + sin(gamma), cos(gamma), 0.0, + 0.0, 0.0, 1.0; + return Ralpha*Rbeta*Rgamma; +} + + +template +ECL_DONT_INLINE Duration product(const MatrixType &a, const MatrixType &b, MatrixType &c) { + StopWatch stopwatch; + c = a*a; + c = a*b; + c = b*b; + return stopwatch.split(); +} + +template +ECL_DONT_INLINE Duration inverse(const MatrixType &a, const MatrixType &b, MatrixType &c) { + StopWatch stopwatch; + c = a.inverse(); + c = b.inverse(); + c = a.inverse(); + return stopwatch.split(); +} + +template +ECL_DONT_INLINE TimeData pose2DTest(bool inverse_test = false) { + TimeData times; + Pose p1, p2, p3; + for ( unsigned int i = 0; i < REPEAT; ++i ) { + p1 = Pose(i*increment, 2*i*increment, 3.14*i*increment); + p2 = Pose(1.2*i*increment, 1.2*2*i*increment, 1.14*i*increment); + if ( inverse_test ) { + times.push_back(inverse(p1,p2,p3)); + } else { + times.push_back(product(p1,p2,p3)); + } + } + return times; +} + +template +ECL_DONT_INLINE TimeData transform2DTest(bool inverse_test = false) { + TimeData times; + MatrixType t1 = MatrixType::Identity(), t2(t1), t3(t1); + for ( unsigned int i = 0; i < REPEAT; ++i ) { + t1.linear() = Rotation2D(3.14*i*increment).toRotationMatrix(); + Vector2d v; v << i*increment, 2*i*increment; + t1.translation() = v; + t2.linear() = Rotation2D(1.14*i*increment).toRotationMatrix(); + t2.translation() = 1.2*v; + if ( inverse_test ) { + times.push_back(inverse(t1,t2,t3)); + } else { + times.push_back(product(t1,t2,t3)); + } + } + return times; +} + +template +ECL_DONT_INLINE TimeData transform3DTest(bool inverse_test = false) { + TimeData times; + MatrixType t1 = MatrixType::Identity(), t2(t1), t3(t1); + for ( unsigned int i = 0; i < REPEAT; ++i ) { + t1.linear() = rotation3D(3.14*i*increment,-3.14*i*increment, 1.0+i*increment ); + Vector3d v; v << i*increment, 2*i*increment, 3*i*increment; + t1.translation() = v; + t2.linear() = rotation3D(3.14*i*increment,-3.14*i*increment, 1.0+i*increment ); + t2.translation() = 1.2*v; + if ( inverse_test ) { + times.push_back(inverse(t1,t2,t3)); + } else { + times.push_back(product(t1,t2,t3)); + } + } + return times; +} + +ECL_DONT_INLINE TimeData rotTrans3DTest(bool inverse_test = false) { + StopWatch stopwatch; + TimeData times; + Matrix3d rot1 = Matrix3d::Identity(), rot2(rot1), rot3; + Vector3d trans1, trans2, trans3; + for ( unsigned int i = 0; i < REPEAT; ++i ) { + rot1 = rotation3D(3.14*i*increment,-3.14*i*increment, 1.0+i*increment ); + rot1 = rotation3D(1.14*i*increment,-1.14*i*increment, 1.2+i*increment ); + trans1 << i*increment, 2*i*increment, 3*i*increment; + trans1 << 2*i*increment, 1*i*increment, 3*i*increment; + if ( inverse_test ) { + stopwatch.restart(); + rot3 = rot2*rot1; + trans3 = rot2*trans1 + trans2; + rot3 = rot1*rot1; + trans3 = rot1*trans1 + trans1; + rot3 = rot2*rot2; + trans3 = rot2*trans2 + trans2; + times.push_back(stopwatch.split()); + } else { // inverse + stopwatch.restart(); + rot3 = rot1.transpose(); + trans3 = rot3*trans1*-1; + rot3 = rot2.transpose(); + trans3 = rot3*trans2*-1; + rot2 = rot3.transpose(); + trans2 = rot2*trans3*-1; + times.push_back(stopwatch.split()); + } + } + return times; +} + +ECL_DONT_INLINE TimeData matrix3DTest(bool inverse_test = false) { + TimeData times; + Matrix4d t1 = Matrix4d::Identity(), t2(t1), t3(t1); + for ( unsigned int i = 0; i < REPEAT; ++i ) { + t1.block<3,3>(0,0) = rotation3D(3.14*i*increment,-3.14*i*increment, 1.0+i*increment ); + Vector3d v; v << i*increment, 2*i*increment, 3*i*increment; + t1.block<3,1>(0,3) = v; + t2.block<3,3>(0,0) = rotation3D(3.14*i*increment,-3.14*i*increment, 1.0+i*increment ); + t2.block<3,1>(0,3) = 1.2*v; + if ( inverse_test ) { + times.push_back(inverse(t1,t2,t3)); + } else { + times.push_back(product(t1,t2,t3)); + } + } + return times; +} + +ECL_DONT_INLINE vector trigTest() { + StopWatch stopwatch; + vector times; + double angle1 = 0.0, angle2 = 1.0, d, e; + const unsigned long repeats = 1000000000L; + double inc = 3.14/static_cast(repeats); + stopwatch.restart(); + for ( unsigned long i = 0; i < repeats; ++i ) { + angle1 += inc; + angle2 -= inc; + d = sin(angle1); + e = cos(angle2); + } + times.push_back(stopwatch.split()); + stopwatch.restart(); + for ( unsigned long i = 0; i < repeats; ++i ) { + angle1 += inc; + angle2 -= inc; + d = angle1*angle2; + e = 3.315*angle1; + } + (void)d; + (void)e; + times.push_back(stopwatch.split()); + return times; +} +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( ecl::StandardException &e ) { + // dont worry about it. + } + + TimeData times; + const bool inverse_test = true; // Just a flag + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Sizes" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Matrix4d : " << sizeof(Matrix4d) << std::endl; + std::cout << "3x3+3x1 : " << sizeof(Matrix3d) + sizeof(Vector3d) << std::endl; + std::cout << "Affine3D : " << sizeof(Transform) << std::endl; + std::cout << "AffineCom3D : " << sizeof(Transform) << std::endl; + std::cout << "Isometr3D : " << sizeof(Transform) << std::endl; + std::cout << "Rotation2D : " << sizeof(Rotation2D) << std::endl; + std::cout << "Translation3D: " << sizeof(Translation) << std::endl; + std::cout << "Quaternion : " << sizeof(Quaternion) << std::endl; +// + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Trig vs *" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + vector trig_times = trigTest(); + std::cout << "Cos+Sin: " << trig_times[0] << std::endl; + std::cout << "Two *'s: " << trig_times[1] << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Products 2D" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + times.clear(); times = pose2DTest(); + std::cout << "Pose2D : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = pose2DTest(); + std::cout << "NewPose2D : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(); + std::cout << "Affine : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(); + std::cout << "CompactAffine: " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(); + std::cout << "Isometry : " << times.average() << " " << times.stdDev() << std::endl; + std::cout << "CompactIso : N/A" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Inverse 2D" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + times.clear(); times = pose2DTest(inverse_test); + std::cout << "Pose2D : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = pose2DTest(inverse_test); + std::cout << "NewPose2D : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(inverse_test); + std::cout << "Affine : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(inverse_test); + std::cout << "CompactAffine: " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform2DTest< Transform >(inverse_test); + std::cout << "Isometry : " << times.average() << " " << times.stdDev() << std::endl; + std::cout << "CompactIso : N/A" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Products 3D" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + times.clear(); times = rotTrans3DTest(); + std::cout << "Rot+Tra : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = matrix3DTest(); + std::cout << "Matrix4d : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(); + std::cout << "Affine : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(); + std::cout << "CompactAffine: " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(); + std::cout << "Isometry : " << times.average() << " " << times.stdDev() << std::endl; + std::cout << "CompactIso : N/A" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Inverse 3D" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + times.clear(); times = rotTrans3DTest(inverse_test); + std::cout << "Rot+Tra : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = matrix3DTest(inverse_test); + std::cout << "Matrix4d : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(inverse_test); + std::cout << "Affine : " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(inverse_test); + std::cout << "CompactAffine: " << times.average() << " " << times.stdDev() << std::endl; + times.clear(); times = transform3DTest< Transform >(inverse_test); + std::cout << "Isometry : " << times.average() << " " << times.stdDev() << std::endl; + std::cout << "CompactIso : N/A" << std::endl; + + std::cout << std::endl; + +// for ( unsigned int i = 0; i < times.data().size(); ++i ) { +// std::cout << times.data()[i] << std::endl; +// } + +// std::cout << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << " Pose Unit Tests" << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << std::endl; +// +// Pose2D p1(1.0,0.0,1.57), p2(0.0,1.0,1.57), p3; +// NewPose2D o1(1.0,0.0,1.57), o2(0.0,1.0,1.57), o3; +// p3 = p2*p1; +// o3 = o2*o1; +// p3.print(); +// o3.print(); +// p3 = p2.inverse(); +// o3 = o2.inverse(); +// p3.print(); +// o3.print(); + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen_sparse.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen_sparse.cpp new file mode 100644 index 0000000..c06c0a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/eigen_sparse.cpp @@ -0,0 +1,166 @@ +/** + * @file /ecl_core_apps/src/benchmarks/eigen_sparse.cpp + * + * + * @brief Benchmark sparse matrix operations for Eigen (ecl_linear_algebra). + * + * @date August 2010 + **/ +/***************************************************************************** +** Preprocessing +*****************************************************************************/ + +#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::linear_algebra::SparseMatrix; +using ecl::linear_algebra::DynamicSparseMatrix; +using ecl::linear_algebra::MatrixXd; +using ecl::StopWatch; + +/***************************************************************************** +** Main +*****************************************************************************/ +#define LM (303) +void test_sparse_matrix( int num ) +{ + DynamicSparseMatrix hh(20, LM); + MatrixXd P(LM,LM); + hh.setZero(); + P.setZero(); + for( int i=0; i<20; i++ ) + for( int j=0; j<3; j++ ) + hh.coeffRef(i,j) = 1; + + for( int i=0; i<10; i++) + { + for( int j=0; j<2; j++ ) + { + for( int k=0; k<3; k++ ) + { + hh.coeffRef( i*2+j, (i*4)+k ) = 1; + } + } + } + + SparseMatrix H(hh); + ecl::StopWatch time; + for( int i=0; i hh(20, LM); + for( int i=0; i +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::StopWatch; +using ecl::TimeStamp; +using ecl::ConfigurationError; +using ecl::StandardException; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +void f1() { + int i = 0; + if ( i == 1 ) {} +} + +void f2() { + int i = 0; + if ( i == 1 ) {} +} + +void f3() { + int i = 0; + if ( i == 1 ) { + throw StandardException(LOC,ConfigurationError); + } +} + +void f4() { + int i = 0; + if ( i == 1 ) { + throw StandardException(LOC,ConfigurationError, "Standard exception with an extra string message."); + } +} + +void f5() { + throw StandardException(LOC,ConfigurationError); +} + +void f6() { + throw StandardException(LOC,ConfigurationError, "Standard exception with an extra string message."); +} + +void g1() { + double dude[5]; + for ( unsigned int j = 0; j < 5; ++j ) { + dude[j] = 3.15*543/230.235; + } + (void)dude; +} + +void g2() { + int i = 0; + double dude[5]; + for ( unsigned int j = 0; j < 5; ++j ) { + dude[j] = 3.15*543/230.235; + } + (void)dude; + if ( i == 1 ) { + throw StandardException(LOC,ConfigurationError, "Standard exception with an extra string message."); + } +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() +{ + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + StopWatch stopwatch; + TimeStamp times[9]; + + stopwatch.restart(); + f1(); + times[0] = stopwatch.split(); + f2(); + times[1] = stopwatch.split(); + f3(); + times[2] = stopwatch.split(); + f4(); + times[3] = stopwatch.split(); + g1(); + times[4] = stopwatch.split(); + g2(); + times[5] = stopwatch.split(); + try { + f2(); + } catch ( StandardException &e ) { + } + times[6] = stopwatch.split(); + try { + f5(); + } catch ( StandardException &e ) {} + times[7] = stopwatch.split(); + try { + f6(); + } catch ( StandardException &e ) {} + times[8] = stopwatch.split(); + + // Try and negate the effects of caching on early instructions (i.e. get right into cache). + stopwatch.restart(); + f1(); + times[0] = stopwatch.split(); + f2(); + times[1] = stopwatch.split(); + f3(); + times[2] = stopwatch.split(); + f4(); + times[3] = stopwatch.split(); + g1(); + times[4] = stopwatch.split(); + g2(); + times[5] = stopwatch.split(); + + try { + f2(); + } catch ( StandardException &e ) { + } + times[6] = stopwatch.split(); + try { + f5(); + } catch ( StandardException &e ) {} + times[7] = stopwatch.split(); + try { + f6(); + } catch ( StandardException &e ) {} + times[8] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Performance comparison ecl exceptions" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Simple Candidate Function " << " Time: " << times[0] << std::endl; + std::cout << " Undeclared exception " << " Time: " << times[1] << std::endl; + std::cout << " Unused exception " << " Time: " << times[2] << std::endl; + std::cout << " Unused exception w/ string " << " Time: " << times[3] << std::endl; + std::cout << std::endl; + std::cout << "Complex Candidate Function " << " Time: " << times[4] << std::endl; + std::cout << " Unused exception w/ string " << " Time: " << times[5] << std::endl; + std::cout << std::endl; + std::cout << "Try Catch Blocks " << std::endl; + std::cout << " Uncaught exceptions " << " Time: " << times[6] << std::endl; + std::cout << " Caught exception " << " Time: " << times[7] << std::endl; + std::cout << " Caught exception w/string " << " Time: " << times[8] << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Conclusions" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "The following conclusions are after testing on a dual core." << std::endl; + std::cout << std::endl; + std::cout << " - In simple functions, unused ecl exceptions < 50ns." << std::endl; + std::cout << " - String messages don't effect the cost of unused ecl exceptions." << std::endl; + std::cout << " - Try-catch blocks have negligible cost." << std::endl; + std::cout << " - String messages do impact caught messages ~1us." << std::endl; + std::cout << std::endl; + return 0; +} + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/files.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/files.cpp new file mode 100644 index 0000000..433dc0d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/files.cpp @@ -0,0 +1,217 @@ +/** + * @file /src/benchmarks/files.cpp + * + * @brief Benchmark comparing various file writing/reading alternatives. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Append; +using ecl::New; +using ecl::OFile; +using ecl::SharedFile; +using ecl::LogStream; +using ecl::TextStream; +using ecl::StandardException; +using ecl::StopWatch; +using ecl::TimeStamp; + +/***************************************************************************** +** Enums +*****************************************************************************/ + +enum LogMode { + Warning, + Error +}; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + + StopWatch stopwatch; + TimeStamp times[22]; + unsigned int lines_to_write = 500;// Buffer::buffer_size/10 + 1; + float f = 33.54; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " OFile Write" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + OFile o_file("odude.txt",New); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + o_file.write("Heya Dude\n",10); + } + o_file.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + o_file.write("Heya Dude\n",10); + } + o_file.flush(); + times[0] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Shared File Write" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + SharedFile s_file("sdude.txt",New); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + s_file.write("Heya Dude\n",10); + } + s_file.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + s_file.write("Heya Dude\n",10); + } + s_file.flush(); + times[1] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " TextStream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + TextStream ostream; + ostream.device().open("dude_stream.txt",New); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << "Heya Dude\n"; + } + ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << "Heya Dude\n"; + } + ostream.flush(); + times[2] = stopwatch.split(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << f << "\n"; + } + ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << f << "\n"; + } + ostream.flush(); + times[3] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " std::ofstream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::ofstream cpp_ostream("dude_ofstream.txt"); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + cpp_ostream << "Heya Dude\n"; + } + cpp_ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + cpp_ostream << "Heya Dude\n"; + } + cpp_ostream.flush(); + times[4] = stopwatch.split(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + cpp_ostream << f << "\n"; + } + cpp_ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + cpp_ostream << f << "\n"; + } + cpp_ostream.flush(); + times[5] = stopwatch.split(); + cpp_ostream.close(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " LogStream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + LogStream log_stream("dude_logstream.txt",New); + log_stream.disableHeader(); + log_stream.disableTimeStamp(); + log_stream.enableMode(Warning,"WARNING"); + + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + LOG(log_stream,Warning) << "Heya Dude\n"; + } + FLUSH(log_stream); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + LOG(log_stream,Warning) << "Heya Dude\n"; + } + FLUSH(log_stream); + times[9] = stopwatch.split(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + LOG(log_stream,Warning) << f << "\n"; + } + FLUSH(log_stream); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + LOG(log_stream,Warning) << f << "\n"; + } + FLUSH(log_stream); + times[10] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Times" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Writing Char Strings:" << std::endl; + std::cout << " OFile write : " << times[0].nsec() << " ns" << std::endl; + std::cout << " SharedFile write : " << times[1].nsec() << " ns" << std::endl; + std::cout << " OFile stream : " << times[2].nsec() << " ns" << std::endl; + std::cout << " LogStream : " << times[9].nsec() << " ns" << std::endl; + std::cout << " C++ ofstream : " << times[4].nsec() << " ns" << std::endl; + std::cout << "Streaming Floats:" << std::endl; + std::cout << " OFileStream : " << times[3].nsec() << " ns" << std::endl; + std::cout << " Log stream : " << times[10].nsec() << " ns" << std::endl; + std::cout << " C++ ofstream : " << times[5].nsec() << " ns" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/flops.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/flops.cpp new file mode 100644 index 0000000..138c23e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/flops.cpp @@ -0,0 +1,687 @@ +/** + * @file /src/benchmarks/flops.cpp + * + * @brief Floating point benchmarking test. + * + * Uses Alburto's code (1992) to calculate the flops using various + * test cases for floating point add/sub/mul/div operations. It also + * takes into account the vectorizability of your code. + * + * This is currently configured to work with POSIX systems. A windows + * equivalent can be configured by changing the macro options early + * in the file. + * + * @date April, 2010. + **/ + +/*---------------- Start Alburto's flops.c source code -----------------*/ + +/*****************************/ +/* flops.c */ +/* Version 2.0, 18 Dec 1992 */ +/* Al Aburto */ +/* aburto@nosc.mil */ +/*****************************/ + +/* + Flops.c is a 'c' program which attempts to estimate your systems + floating-point 'MFLOPS' rating for the FADD, FSUB, FMUL, and FDIV + operations based on specific 'instruction mixes' (discussed below). + The program provides an estimate of PEAK MFLOPS performance by making + maximal use of register variables with minimal interaction with main + memory. The execution loops are all small so that they will fit in + any cache. Flops.c can be used along with Linpack and the Livermore + kernels (which exersize memory much more extensively) to gain further + insight into the limits of system performance. The flops.c execution + modules also include various percent weightings of FDIV's (from 0% to + 25% FDIV's) so that the range of performance can be obtained when + using FDIV's. FDIV's, being computationally more intensive than + FADD's or FMUL's, can impact performance considerably on some systems. + + Flops.c consists of 8 independent modules (routines) which, except for + module 2, conduct numerical integration of various functions. Module + 2, estimates the value of pi based upon the Maclaurin series expansion + of atan(1). MFLOPS ratings are provided for each module, but the + programs overall results are summerized by the MFLOPS(1), MFLOPS(2), + MFLOPS(3), and MFLOPS(4) outputs. + + The MFLOPS(1) result is identical to the result provided by all + previous versions of flops.c. It is based only upon the results from + modules 2 and 3. Two problems surfaced in using MFLOPS(1). First, it + was difficult to completely 'vectorize' the result due to the + recurrence of the 's' variable in module 2. This problem is addressed + in the MFLOPS(2) result which does not use module 2, but maintains + nearly the same weighting of FDIV's (9.2%) as in MFLOPS(1) (9.6%). + The second problem with MFLOPS(1) centers around the percentage of + FDIV's (9.6%) which was viewed as too high for an important class of + problems. This concern is addressed in the MFLOPS(3) result where NO + FDIV's are conducted at all. + + The number of floating-point instructions per iteration (loop) is + given below for each module executed: + + MODULE FADD FSUB FMUL FDIV TOTAL Comment + 1 7 0 6 1 14 7.1% FDIV's + 2 3 2 1 1 7 difficult to vectorize. + 3 6 2 9 0 17 0.0% FDIV's + 4 7 0 8 0 15 0.0% FDIV's + 5 13 0 15 1 29 3.4% FDIV's + 6 13 0 16 0 29 0.0% FDIV's + 7 3 3 3 3 12 25.0% FDIV's + 8 13 0 17 0 30 0.0% FDIV's + + A*2+3 21 12 14 5 52 A=5, MFLOPS(1), Same as + 40.4% 23.1% 26.9% 9.6% previous versions of the + flops.c program. Includes + only Modules 2 and 3, does + 9.6% FDIV's, and is not + easily vectorizable. + + 1+3+4 58 14 66 14 152 A=4, MFLOPS(2), New output + +5+6+ 38.2% 9.2% 43.4% 9.2% does not include Module 2, + A*7 but does 9.2% FDIV's. + + 1+3+4 62 5 74 5 146 A=0, MFLOPS(3), New output + +5+6+ 42.9% 3.4% 50.7% 3.4% does not include Module 2, + 7+8 but does 3.4% FDIV's. + + 3+4+6 39 2 50 0 91 A=0, MFLOPS(4), New output + +8 42.9% 2.2% 54.9% 0.0% does not include Module 2, + and does NO FDIV's. + + NOTE: Various timer routines are included as indicated below. The + timer routines, with some comments, are attached at the end + of the main program. + + NOTE: Please do not remove any of the printouts. + + EXAMPLE COMPILATION: + UNIX based systems + cc -DUNIX -O flops.c -o flops + cc -DUNIX -DROPT flops.c -o flops + cc -DUNIX -fast -O4 flops.c -o flops + . + . + . + etc. + + Al Aburto + aburto@nosc.mil +*/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::CmdLine; +using ecl::StandardException; + +/***************************************************************************** +** dtime() : Uses Posix .1 calls to evaluate the time. +*****************************************************************************/ + +#if defined(ECL_IS_WIN32) +#include + +int dtime(double *p) +{ + double q; + + q = p[2]; + + p[2] = (double)GetTickCount() * 1.0e-03; + p[1] = p[2] - q; + + return 0; +} +#elif defined(ECL_IS_POSIX) +#include +#include +#include + +int dtime(double *p) +{ + static struct tms tms; + + double q; + times(&tms); + q = p[2]; + p[2] = (double)tms.tms_utime / (double)_SC_CLK_TCK; + p[1] = p[2] - q; + return 0; +} +#endif + + +/***************************************************************************** +** Main program +*****************************************************************************/ +int main(int argc, char** argv) +{ + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + + CmdLine cmd("Benchmarks the speed of computation (mflops) on this machine."); + cmd.parse(argc,argv); + + /***************************************************************************** + ** Variables + *****************************************************************************/ + + double nulltime, TimeArray[3]{}; /* Variables needed for 'dtime()'. */ + double TLimit; /* Threshold to determine Number of */ + /* Loops to run. Fixed at 15.0 seconds.*/ + + double T[36]; /* Global Array used to hold timing */ + /* results and other information. */ + + double sa,sb,sc,one,two,three; + double four,five,piref,piprg; + double scale,pierr; + + double A0 = 1.0; + double A1 = -0.1666666666671334; + double A2 = 0.833333333809067E-2; + double A3 = 0.198412715551283E-3; + double A4 = 0.27557589750762E-5; + double A5 = 0.2507059876207E-7; + double A6 = 0.164105986683E-9; + + double B1 = -0.4999999999982; + double B2 = 0.4166666664651E-1; + double B3 = -0.1388888805755E-2; + double B4 = 0.24801428034E-4; + double B5 = -0.2754213324E-6; + double B6 = 0.20189405E-8; + + double D1 = 0.3999999946405E-1; + double D2 = 0.96E-3; + double D3 = 0.1233153E-5; + + double E2 = 0.48E-3; + double E3 = 0.411051E-6; + + double s,u,v,w,x; + + long loops, NLimit; + long i, m, n; + + printf("\n"); + printf(" FLOPS C Program (Double Precision), V2.0 18 Dec 1992\n\n"); + + /****************************/ + loops = 15625; /* Initial number of loops. */ + /* DO NOT CHANGE! */ + /****************************/ + + /****************************************************/ + /* Set Variable Values. */ + /* T[1] references all timing results relative to */ + /* one million loops. */ + /* */ + /* The program will execute from 31250 to 512000000 */ + /* loops based on a runtime of Module 1 of at least */ + /* TLimit = 15.0 seconds. That is, a runtime of 15 */ + /* seconds for Module 1 is used to determine the */ + /* number of loops to execute. */ + /* */ + /* No more than NLimit = 512000000 loops are allowed*/ + /****************************************************/ + + T[1] = 1.0E+06/(double)loops; + + TLimit = 15.0; + NLimit = 512000000; + + piref = 3.14159265358979324; + one = 1.0; + two = 2.0; + three = 3.0; + four = 4.0; + five = 5.0; + + printf(" Module Error RunTime MFLOPS Math Calculation Operations\n"); + printf(" (usec)\n"); + /*************************/ + /* Initialize the timer. */ + /*************************/ + + dtime(TimeArray); + dtime(TimeArray); + + /*******************************************************/ + /* Module 1. Calculate integral of df(x)/f(x) defined */ + /* below. Result is ln(f(1)). There are 14 */ + /* double precision operations per loop */ + /* ( 7 +, 0 -, 6 *, 1 / ) that are included */ + /* in the timing. */ + /* 50.0% +, 00.0% -, 42.9% *, and 07.1% / */ + /*******************************************************/ + n = loops; + sa = 0.0; + + s = 0.0; // Initialising to remove warning + x = 0.0; + + while ( sa < TLimit ) + { + n = 2 * n; + x = one / (double)n; /*********************/ + s = 0.0; /* Loop 1. */ + v = 0.0; /*********************/ + w = one; + + dtime(TimeArray); + for( i = 1 ; i <= n-1 ; i++ ) + { + v = v + w; + u = v * x; + s = s + (D1+u*(D2+u*D3))/(w+u*(D1+u*(E2+u*E3))); + } + dtime(TimeArray); + sa = TimeArray[1]; + + if ( n == NLimit ) + { + break; + } + /* printf(" %10ld %12.5lf\n",n,sa); */ + } + + scale = 1.0E+06 / (double)n; + T[1] = scale; + + /****************************************/ + /* Estimate nulltime ('for' loop time). */ + /****************************************/ + dtime(TimeArray); + for( i = 1 ; i <= n-1 ; i++ ) + { + } + dtime(TimeArray); + nulltime = T[1] * TimeArray[1]; + if ( nulltime < 0.0 ) + { + nulltime = 0.0; + } + + T[2] = T[1] * sa - nulltime; + + sa = (D1+D2+D3)/(one+D1+E2+E3); + sb = D1; + + T[3] = T[2] / 14.0; /*********************/ + sa = x * ( sa + sb + two * s ) / two; /* Module 1 Results. */ + sb = one / sa; /*********************/ + n = (long)( (double)( 40000 * (long)sb ) / scale ); + sc = sb - 25.2; + T[4] = one / T[3]; + /********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /********************/ + printf(" 1 %13.4le %10.4lf %10.4lf Integration [ 7+, 0-, 6*, 1/]\n",sc,T[2],T[4]); + + m = n; + + /*******************************************************/ + /* Module 2. Calculate value of PI from Taylor Series */ + /* expansion of atan(1.0). There are 7 */ + /* double precision operations per loop */ + /* ( 3 +, 2 -, 1 *, 1 / ) that are included */ + /* in the timing. */ + /* 42.9% +, 28.6% -, 14.3% *, and 14.3% / */ + /*******************************************************/ + + s = -five; /********************/ + sa = -one; /* Loop 2. */ + /********************/ + dtime(TimeArray); + for ( i = 1 ; i <= m ; i++ ) + { + s = -s; + sa = sa + s; + } + dtime(TimeArray); + T[5] = T[1] * TimeArray[1]; + if ( T[5] < 0.0 ) + { + T[5] = 0.0; + } + + sc = (double)m; + + u = sa; /*********************/ + v = 0.0; /* Loop 3. */ + w = 0.0; /*********************/ + x = 0.0; + + dtime(TimeArray); + for ( i = 1 ; i <= m ; i++) + { + s = -s; + sa = sa + s; + u = u + two; + x = x +(s - u); + v = v - s * u; + w = w + s / u; + } + dtime(TimeArray); + T[6] = T[1] * TimeArray[1]; + + T[7] = ( T[6] - T[5] ) / 7.0; /*********************/ + m = (long)( sa * x / sc ); /* PI Results */ + sa = four * w / five; /*********************/ + sb = sa + five / v; + sc = 31.25; + piprg = sb - sc / (v * v * v); + pierr = piprg - piref; + T[8] = one / T[7]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 2 %13.4le %10.4lf %10.4lf Taylor Series [ 3+, 2-, 1*, 1/]\n",pierr,T[6]-T[5],T[8]); + + /*******************************************************/ + /* Module 3. Calculate integral of sin(x) from 0.0 to */ + /* PI/3.0 using Trapazoidal Method. Result */ + /* is 0.5. There are 17 double precision */ + /* operations per loop (6 +, 2 -, 9 *, 0 /) */ + /* included in the timing. */ + /* 35.3% +, 11.8% -, 52.9% *, and 00.0% / */ + /*******************************************************/ + + x = piref / ( three * (double)m ); /*********************/ + s = 0.0; /* Loop 4. */ + v = 0.0; /*********************/ + + dtime(TimeArray); + for( i = 1 ; i <= m-1 ; i++ ) + { + v = v + one; + u = v * x; + w = u * u; + s = s + u * ((((((A6*w-A5)*w+A4)*w-A3)*w+A2)*w+A1)*w+one); + } + dtime(TimeArray); + T[9] = T[1] * TimeArray[1] - nulltime; + + u = piref / three; + w = u * u; + sa = u * ((((((A6*w-A5)*w+A4)*w-A3)*w+A2)*w+A1)*w+one); + + T[10] = T[9] / 17.0; /*********************/ + sa = x * ( sa + two * s ) / two; /* sin(x) Results. */ + sb = 0.5; /*********************/ + sc = sa - sb; + T[11] = one / T[10]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 3 %13.4le %10.4lf %10.4lf Trapezoidal Sum (sin) [ 6+, 2-, 9*, 0/]\n",sc,T[9],T[11]); + + /************************************************************/ + /* Module 4. Calculate Integral of cos(x) from 0.0 to PI/3 */ + /* using the Trapazoidal Method. Result is */ + /* sin(PI/3). There are 15 double precision */ + /* operations per loop (7 +, 0 -, 8 *, and 0 / ) */ + /* included in the timing. */ + /* 50.0% +, 00.0% -, 50.0% *, 00.0% / */ + /************************************************************/ + A3 = -A3; + A5 = -A5; + x = piref / ( three * (double)m ); /*********************/ + s = 0.0; /* Loop 5. */ + /*********************/ + dtime(TimeArray); + for( i = 1 ; i <= m-1 ; i++ ) + { + u = (double)i * x; + w = u * u; + s = s + w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + } + dtime(TimeArray); + T[12] = T[1] * TimeArray[1] - nulltime; + + u = piref / three; + w = u * u; + sa = w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + + T[13] = T[12] / 15.0; /*******************/ + sa = x * ( sa + one + two * s ) / two; /* Module 4 Result */ + u = piref / three; /*******************/ + w = u * u; + sb = u * ((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+A0); + sc = sa - sb; + T[14] = one / T[13]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 4 %13.4le %10.4lf %10.4lf Trapezoidal Sum (cos) [ 7+, 0-, 8*, 0/]\n",sc,T[12],T[14]); + + /************************************************************/ + /* Module 5. Calculate Integral of tan(x) from 0.0 to PI/3 */ + /* using the Trapazoidal Method. Result is */ + /* ln(cos(PI/3)). There are 29 double precision */ + /* operations per loop (13 +, 0 -, 15 *, and 1 /)*/ + /* included in the timing. */ + /* 46.7% +, 00.0% -, 50.0% *, and 03.3% / */ + /************************************************************/ + + x = piref / ( three * (double)m ); /*********************/ + s = 0.0; /* Loop 6. */ + /*********************/ + dtime(TimeArray); + for( i = 1 ; i <= m-1 ; i++ ) + { + u = (double)i * x; + w = u * u; + v = u * ((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + s = s + v / (w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one); + } + dtime(TimeArray); + T[15] = T[1] * TimeArray[1] - nulltime; + + u = piref / three; + w = u * u; + sa = u*((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + sb = w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + sa = sa / sb; + + T[16] = T[15] / 29.0; /*******************/ + sa = x * ( sa + two * s ) / two; /* Module 5 Result */ + sb = 0.6931471805599453; /*******************/ + sc = sa - sb; + T[17] = one / T[16]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 5 %13.4le %10.4lf %10.4lf Trapezoidal Sum (tan) [13+, 0-,15*, 1/]\n",sc,T[15],T[17]); + + /************************************************************/ + /* Module 6. Calculate Integral of sin(x)*cos(x) from 0.0 */ + /* to PI/4 using the Trapazoidal Method. Result */ + /* is sin(PI/4)^2. There are 29 double precision */ + /* operations per loop (13 +, 0 -, 16 *, and 0 /)*/ + /* included in the timing. */ + /* 46.7% +, 00.0% -, 53.3% *, and 00.0% / */ + /************************************************************/ + + x = piref / ( four * (double)m ); /*********************/ + s = 0.0; /* Loop 7. */ + /*********************/ + dtime(TimeArray); + for( i = 1 ; i <= m-1 ; i++ ) + { + u = (double)i * x; + w = u * u; + v = u * ((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + s = s + v*(w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one); + } + dtime(TimeArray); + T[18] = T[1] * TimeArray[1] - nulltime; + + u = piref / four; + w = u * u; + sa = u*((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + sb = w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + sa = sa * sb; + + T[19] = T[18] / 29.0; /*******************/ + sa = x * ( sa + two * s ) / two; /* Module 6 Result */ + sb = 0.25; /*******************/ + sc = sa - sb; + T[20] = one / T[19]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 6 %13.4le %10.4lf %10.4lf Trapezoidal Sum (sin*cos) [13+, 0-,16*, 0/]\n",sc,T[18],T[20]); + + + /*******************************************************/ + /* Module 7. Calculate value of the definite integral */ + /* from 0 to sa of 1/(x+1), x/(x*x+1), and */ + /* x*x/(x*x*x+1) using the Trapizoidal Rule.*/ + /* There are 12 double precision operations */ + /* per loop ( 3 +, 3 -, 3 *, and 3 / ) that */ + /* are included in the timing. */ + /* 25.0% +, 25.0% -, 25.0% *, and 25.0% / */ + /*******************************************************/ + + /*********************/ + s = 0.0; /* Loop 8. */ + w = one; /*********************/ + sa = 102.3321513995275; + v = sa / (double)m; + + dtime(TimeArray); + for ( i = 1 ; i <= m-1 ; i++) + { + x = (double)i * v; + u = x * x; + s = s - w / ( x + w ) - x / ( u + w ) - u / ( x * u + w ); + } + dtime(TimeArray); + T[21] = T[1] * TimeArray[1] - nulltime; + /*********************/ + /* Module 7 Results */ + /*********************/ + T[22] = T[21] / 12.0; + x = sa; + u = x * x; + sa = -w - w / ( x + w ) - x / ( u + w ) - u / ( x * u + w ); + sa = 18.0 * v * (sa + two * s ); + + m = -2000 * (long)sa; + m = (long)( (double)m / scale ); + + sc = sa + 500.2; + T[23] = one / T[22]; + /********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /********************/ + printf(" 7 %13.4le %10.4lf %10.4lf Trapezoidal Sum (polynomial) [ 3+, 3-, 3*, 3/]\n",sc,T[21],T[23]); + + /************************************************************/ + /* Module 8. Calculate Integral of sin(x)*cos(x)*cos(x) */ + /* from 0 to PI/3 using the Trapazoidal Method. */ + /* Result is (1-cos(PI/3)^3)/3. There are 30 */ + /* double precision operations per loop included */ + /* in the timing: */ + /* 13 +, 0 -, 17 * 0 / */ + /* 46.7% +, 00.0% -, 53.3% *, and 00.0% / */ + /************************************************************/ + + x = piref / ( three * (double)m ); /*********************/ + s = 0.0; /* Loop 9. */ + /*********************/ + dtime(TimeArray); + for( i = 1 ; i <= m-1 ; i++ ) + { + u = (double)i * x; + w = u * u; + v = w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + s = s + v*v*u*((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + } + dtime(TimeArray); + T[24] = T[1] * TimeArray[1] - nulltime; + + u = piref / three; + w = u * u; + sa = u*((((((A6*w+A5)*w+A4)*w+A3)*w+A2)*w+A1)*w+one); + sb = w*(w*(w*(w*(w*(B6*w+B5)+B4)+B3)+B2)+B1)+one; + sa = sa * sb * sb; + + T[25] = T[24] / 30.0; /*******************/ + sa = x * ( sa + two * s ) / two; /* Module 8 Result */ + sb = 0.29166666666666667; /*******************/ + sc = sa - sb; + T[26] = one / T[25]; + /*********************/ + /* DO NOT REMOVE */ + /* THIS PRINTOUT! */ + /*********************/ + printf(" 8 %13.4le %10.4lf %10.4lf Trapezoidal Sum (sin*cos*cos) [13+, 0-,17*, 0/]\n",sc,T[24],T[26]); + + /**************************************************/ + /* MFLOPS(1) output. This is the same weighting */ + /* used for all previous versions of the flops.c */ + /* program. Includes Modules 2 and 3 only. */ + /**************************************************/ + T[27] = ( five * (T[6] - T[5]) + T[9] ) / 52.0; + T[28] = one / T[27]; + + /**************************************************/ + /* MFLOPS(2) output. This output does not include */ + /* Module 2, but it still does 9.2% FDIV's. */ + /**************************************************/ + T[29] = T[2] + T[9] + T[12] + T[15] + T[18]; + T[29] = (T[29] + four * T[21]) / 152.0; + T[30] = one / T[29]; + + /**************************************************/ + /* MFLOPS(3) output. This output does not include */ + /* Module 2, but it still does 3.4% FDIV's. */ + /**************************************************/ + T[31] = T[2] + T[9] + T[12] + T[15] + T[18]; + T[31] = (T[31] + T[21] + T[24]) / 146.0; + T[32] = one / T[31]; + + /**************************************************/ + /* MFLOPS(4) output. This output does not include */ + /* Module 2, and it does NO FDIV's. */ + /**************************************************/ + T[33] = (T[9] + T[12] + T[18] + T[24]) / 91.0; + T[34] = one / T[33]; + + + printf("\n"); + printf("Averaging various groups above\n"); + printf("\n"); + printf(" Iterations = %10ld\n",m); + printf(" NullTime (usec) = %10.4lf\n",nulltime); + printf(" MFLOPS(1) = %10.4lf [generic 2,3 only]\n",T[28]); + printf(" MFLOPS(2) = %10.4lf [9.2%% fp divisions]\n",T[30]); + printf(" MFLOPS(3) = %10.4lf [3.4%% fp divisions]\n",T[32]); + printf(" MFLOPS(4) = %10.4lf [0.0%% fp divisions]\n\n",T[34]); + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/snooze.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/snooze.cpp new file mode 100644 index 0000000..c3e45cb --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/snooze.cpp @@ -0,0 +1,134 @@ +/** + * @file /src/benchmarks/snooze.cpp + * + * @brief Benchmark for the absolute periodic timers (snoozers). + * + * @date December 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace benchmarks { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Duration; +using ecl::Snooze; +using ecl::StandardException; + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class LogSnooze : public Snooze { + +public: + LogSnooze(const long &ms) : Snooze(Duration(0,ms*1000000L)), count(0), avg(0.0), avg_noise(0.0), max(0), period_ms(ms) {}; + + // Need to run this at least 10 times before the average is close + // to correct. + void log() { + ecl::epoch_time(time_actual); + latency = (time_actual.tv_nsec - time_value.tv_nsec)/1000000.0; // convert to ms + if ( count == 0 ) { + avg = latency; + } else { + avg = 0.9*avg + 0.1*latency; + avg_noise = 0.9*avg_noise + 0.1*fabs(latency-avg); + } + if ( latency > max ) { max = latency; } + ++count; + } + + void printLog() { + std::cout << "Loop period [ms]: " << period_ms << std::endl; + std::cout << "Average latency [ms]: " << avg << std::endl; + std::cout << "Maximum latency [ms]: " << max << std::endl; + } + +private: + /********************* + ** Logging Variables + **********************/ + TimeStructure time_actual; + double latency; + int count; + double avg,avg_noise; + double max; + long period_ms; +}; + + +} // namespace benchmarks +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::benchmarks; + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main() { + + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Snooze Latency" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* " << std::endl; + std::cout << "* Latency is the absolute time behind where it should be." << std::endl; + std::cout << "* This is only a factor for the first snooze loop." << std::endl; + std::cout << "*" << std::endl; + std::cout << "* Latency noise is more important. After the first loop," << std::endl; + std::cout << "* with an ideal noise value of zero, the loop will time" << std::endl; + std::cout << "* exactly as you specify. Practically, this is not the case," << std::endl; + std::cout << "* but you should get good results from this without having" << std::endl; + std::cout << "* to use system timers. Use with loops which need to be" << std::endl; + std::cout << "* 5ms or over. Faster loops really require a RTOS." << std::endl; + std::cout << "* " << std::endl; + std::cout << "*****************************************************************" << std::endl; + std::cout << std::endl; + std::cout << "Looping commencing..." << std::endl; + + LogSnooze snooze(30); + snooze.initialise(); // Get it ready to start looping. + for(int i = 0; i < 100; ++i ) { + snooze(); + snooze.log(); + } + snooze.printLog(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/streams.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/streams.cpp new file mode 100644 index 0000000..1766b5f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/streams.cpp @@ -0,0 +1,150 @@ +/** + * @file /src/benchmarks/streams.cpp + * + * @brief Benchmark streams to standard output. + * + * Benchmark various means of streaming to standard output. + * + * @date November 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::OConsoleStream; +using ecl::StopWatch; +using ecl::TimeStamp; +using ecl::Format; +using ecl::StandardException; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + + StopWatch stopwatch; + TimeStamp times[6]; + unsigned int lines_to_write = 1; + float f = 33.54235235; + Format format; format.precision(2); format.width(5); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Printf" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + printf("Heya Dude\n"); + } + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + printf("Heya Dude\n"); + } + times[0] = stopwatch.split(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + printf("%4.2f \n",f); + } + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + printf("%4.2f \n",f); + } + times[3] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Cout" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + std::cout << "Heya Dude\n"; + } + std::cout.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + std::cout << "Heya Dude\n"; + } + std::cout.flush(); + times[1] = stopwatch.split(); + + std::cout.precision(4); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + std::cout << f << " \n"; + } + std::cout.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + std::cout << f << " \n"; + } + std::cout.flush(); + times[4] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Ostream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + OConsoleStream ostream; + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + ostream << "Heya Dude\n"; + } + ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << "Heya Dude\n"; + } + ostream.flush(); + times[2] = stopwatch.split(); + + for ( unsigned int i = 0; i < lines_to_write; ++i ) { // Avoid speedups from caching affecting times. + ostream << format(f) << " \n"; + } + ostream.flush(); + stopwatch.restart(); + for ( unsigned int i = 0; i < lines_to_write; ++i ) { + ostream << format(f) << " \n"; + } + ostream.flush(); + times[5] = stopwatch.split(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Times" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Writing Char Strings:" << std::endl; + std::cout << " printf : " << times[0].nsec() << " ns" << std::endl; + std::cout << " cout : " << times[1].nsec() << " ns" << std::endl; + std::cout << " OConsoleStream : " << times[2].nsec() << " ns" << std::endl; + std::cout << "Streaming Floats:" << std::endl; + std::cout << " printf : " << times[3].nsec() << " ns" << std::endl; + std::cout << " cout : " << times[4].nsec() << " ns" << std::endl; + std::cout << " OConsoleStream : " << times[5].nsec() << " ns" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/string_conversions.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/string_conversions.cpp new file mode 100644 index 0000000..446c939 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/benchmarks/string_conversions.cpp @@ -0,0 +1,172 @@ +/** + * @file /src/benchmarks/string_conversions.cpp + * + * @brief Benchmarks the performance of various string conversions. + * + * Benchmarks the performance of various string converters. Namely the + * c sprintf, the c++ ostringstream and ecl's converters (refer to + * package ecl_utilities). + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +//#include +//#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using std::ostringstream; +using ecl::StopWatch; +using ecl::TimeStamp; +using ecl::Converter; +using ecl::StandardException; + +/***************************************************************************** +** Main +*****************************************************************************/ + + +int main() +{ + try { + ecl::set_priority(ecl::RealTimePriority4); + } catch ( StandardException &e ) { + // dont worry about it. + } + StopWatch stopwatch; + TimeStamp time_converters[10], time_sprintf[10], time_iostreams[10]; + + string str; + int i = -11; + unsigned int ui = 123; + long l = -211123; + float f = -16.123f; + double d = -2316.1234; + char buffer[30]; + char* char_string; + Converter toCharString; + ostringstream ostream; + + for (int j = 0; j < 50; ++j ) { + sprintf(buffer,"%d",i); // First sprintf is always slow, it caches some crap I think. + sprintf(buffer,"%f",f); // Like above, but for floats. + ostream << i; // Ditto + ostream << l; // Ditto + } + + /********************* + ** Sprintf + **********************/ + stopwatch.restart(); + sprintf(buffer,"%d",i); + time_sprintf[0] = stopwatch.split(); + sprintf(buffer,"%d",ui); + time_sprintf[1] = stopwatch.split(); + sprintf(buffer,"%ld",l); + time_sprintf[2] = stopwatch.split(); + sprintf(buffer,"%f",f); + time_sprintf[3] = stopwatch.split(); + sprintf(buffer,"%lf",d); + time_sprintf[4] = stopwatch.split(); + + /********************* + ** IOStreams + **********************/ + stopwatch.restart(); + ostream << i; + time_iostreams[0] = stopwatch.split(); + ostream << ui; + time_iostreams[1] = stopwatch.split(); + ostream << l; + time_iostreams[2] = stopwatch.split(); + ostream << f; + time_iostreams[3] = stopwatch.split(); + ostream << d; + time_iostreams[4] = stopwatch.split(); + +// /********************* +// ** FastFormat +// **********************/ +// char char_buffer[250]; +// TimeStamp time_ff[10]; +// fastformat::sinks::char_buffer_sink ff_char_buffer(250,char_buffer); +// fastformat::write(ff_char_buffer, i); +// fastformat::write(ff_char_buffer, l); +// stopwatch.restart(); +// fastformat::write(ff_char_buffer, i); +// time_ff[0] = stopwatch.split(); +// fastformat::write(ff_char_buffer, l); +// time_ff[1] = stopwatch.split(); +//// fastformat::write(ff_char_buffer, f); +// time_ff[2] = stopwatch.split(); +//// fastformat::write(ff_char_buffer, d); +// time_ff[3] = stopwatch.split(); +// + /********************* + ** Converter + **********************/ + char_string = toCharString(f); + char_string = toCharString(f); + char_string = toCharString(f); + char_string = toCharString(f); + stopwatch.restart(); + char_string = toCharString(i); + time_converters[0] = stopwatch.split(); + char_string = toCharString(ui); + time_converters[1] = stopwatch.split(); + char_string = toCharString(l); + time_converters[2] = stopwatch.split(); + char_string = toCharString(f); + time_converters[3] = stopwatch.split(); + char_string = toCharString(d); + time_converters[4] = stopwatch.split(); + + (void)char_string; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Performance comparison of char string conversion apis" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Converter(int) " << " Time: " << time_converters[0] << std::endl; + std::cout << "Converter(unsigned int) " << " Time: " << time_converters[1] << std::endl; + std::cout << "Converter(long) " << " Time: " << time_converters[2] << std::endl; + std::cout << "Converter(float) " << " Time: " << time_converters[3] << std::endl; + std::cout << "Converter(double) " << " Time: " << time_converters[4] << std::endl; + std::cout << std::endl; + std::cout << "sprintf(int) " << " Time: " << time_sprintf[0] << std::endl; + std::cout << "sprintf(unsigned int) " << " Time: " << time_sprintf[1] << std::endl; + std::cout << "sprintf(long) " << " Time: " << time_sprintf[2] << std::endl; + std::cout << "sprintf(float) " << " Time: " << time_sprintf[3] << std::endl; + std::cout << "sprintf(double) " << " Time: " << time_sprintf[4] << std::endl; + std::cout << std::endl; + std::cout << "ostringstream(int) " << " Time: " << time_iostreams[0] << std::endl; + std::cout << "ostringstream(unsigned int) " << " Time: " << time_iostreams[1] << std::endl; + std::cout << "ostringstream(long) " << " Time: " << time_iostreams[2] << std::endl; + std::cout << "ostringstream(float) " << " Time: " << time_iostreams[3] << std::endl; + std::cout << "ostringstream(double) " << " Time: " << time_iostreams[4] << std::endl; + std::cout << std::endl; +// std::cout << "fastformat(int) " << " Time: " << time_ff[0] << std::endl; +// std::cout << "fastformat(long) " << " Time: " << time_ff[1] << std::endl; +// std::cout << "fastformat(float) " << " Time: " << time_ff[2] << std::endl; +// std::cout << "fastformat(double) " << " Time: " << time_ff[3] << std::endl; +// std::cout << std::endl; + + return 0; +} + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/CMakeLists.txt new file mode 100644 index 0000000..ff84579 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/CMakeLists.txt @@ -0,0 +1,66 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_add_utility name) + add_executable(ecl_${name} ${name}.cpp) + target_link_libraries( + ecl_${name} + PRIVATE + ecl_config::ecl_config + ecl_command_line::ecl_command_line + ecl_converters::ecl_converters + ecl_containers::ecl_containers + ecl_devices::ecl_devices + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_ipc::ecl_ipc + ecl_linear_algebra::ecl_linear_algebra + ecl_sigslots::ecl_sigslots + ecl_streams::ecl_streams + ecl_threads::ecl_threads + ecl_time_lite::ecl_time_lite + ecl_type_traits::ecl_type_traits + ) + install(TARGETS ecl_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +macro(ecl_add_global_utility name) + add_executable(ecl_${name} ${name}.cpp) + target_link_libraries( + ecl_${name} + PRIVATE + ecl_config::ecl_config + ecl_command_line::ecl_command_line + ecl_converters::ecl_converters + ecl_containers::ecl_containers + ecl_devices::ecl_devices + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_ipc::ecl_ipc + ecl_linear_algebra::ecl_linear_algebra + ecl_sigslots::ecl_sigslots + ecl_streams::ecl_streams + ecl_threads::ecl_threads + ecl_time_lite::ecl_time_lite + ecl_type_traits::ecl_type_traits + ) + set_target_properties(ecl_${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) + install(TARGETS ecl_${name} RUNTIME DESTINATION bin) +endmacro() + +############################################################################### +# Setup +############################################################################### + +ecl_add_utility(hex) +ecl_add_utility(serial) +ecl_add_utility(socket_client) +ecl_add_utility(socket_server) +ecl_add_global_utility(process_statistics) +ecl_add_global_utility(quaternion2yaw) +ecl_add_global_utility(yaw2quaternion) diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/hex.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/hex.cpp new file mode 100644 index 0000000..b85737b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/hex.cpp @@ -0,0 +1,225 @@ +/** + * @file /src/utils/hex.cpp + * + * @brief Utility for testing a serial port connection using hex magic only. + * + * @date March 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace utils { + +/***************************************************************************** + * Using + ****************************************************************************/ + +using std::string; +using std::vector; +using ecl::ArgException; +using ecl::CmdLine; +using ecl::SwitchArg; +using ecl::ValueArg; +using ecl::Serial; +using ecl::BaudRate; +using ecl::BaudRate_9600; +using ecl::BaudRate_38400; +using ecl::BaudRate_115200; +using ecl::DataBits_8; +using ecl::StopBits_1; +using ecl::NoParity; +using ecl::StandardException; +using ecl::Format; +using ecl::Dec; +using ecl::Hex; +using ecl::NoAlign; +using ecl::RightAlign; +using ecl::Thread; +using ecl::TimeStamp; +using ecl::MilliSleep; +using ecl::Converter; + +/***************************************************************************** + * Classes + ****************************************************************************/ + +class Writer +{ +public: + Writer(Serial *serial_device, bool timestamps = false) : + display_timestamps(timestamps), + serial(serial_device), + hex_format(-1,NoAlign,Hex), + thread(&Writer::run,*this) + { (void) current_time; } + void wait() { thread.join(); } + +private: + bool display_timestamps; + long current_time; + TimeStamp timestamp; + Serial *serial; + Format hex_format; + Thread thread; + Converter< vector > toByteArray; + + void run() { + MilliSleep sleep; + string s; + char buffer[80]; + + /****************************************** + ** Read + *******************************************/ + while (1) { + // Read a line from standard input + if ( fgets(buffer,80,stdin) == NULL ) { + break; + } + // fgets always terminates with a null character, even if it manages + // to read n-1 chars + vector hex_values = toByteArray(buffer); +// std::cout << "Sending: "; +// for ( unsigned int i = 0; i < hex_values.size(); ++i ) { +// std::cout << hex_format(hex_values[i]) << " "; +// } + std::cout << std::endl; + serial->write(&hex_values[0],hex_values.size()); + if ( display_timestamps ) { + timestamp.stamp(); + std::cout << "[" << timestamp << "]" << std::endl; + } + sleep(5); + } + } +}; + +class Reader +{ +public: + Reader(Serial *serial_device, bool timestamps = false) : + serial(serial_device), + display_timestamps(timestamps), + format(6,RightAlign,Dec), + hex_format(-1,NoAlign,Hex), + thread(&Reader::run,*this) + { (void) current_time; } + + void wait() { thread.join(); } + +private: + void run() { + char s[255]; + unsigned long ch_read; + + while (1) { + ch_read = serial->read(s,1); +// ch_read = serial->read(s,255); + if ( ch_read > 0 ) { + if ( display_timestamps ) { + time.stamp(); + std::cout << "[" << time << "] "; + } + for (unsigned int i = 0; i < ch_read; ++i) { + std::cout << hex_format(s[i]) << " "; + } + std::cout << std::endl; + } else { +// std::cout << "Timed out." << std::endl; + } + } + } + Serial *serial; + bool display_timestamps; + long current_time; + TimeStamp time; + Format format; + Format hex_format; + Thread thread; + +}; + +} // namespace utils +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::utils; + +/***************************************************************************** +** Main program +*****************************************************************************/ +int main(int argc, char** argv) { + + /****************************************** + * Parse for the port name + ******************************************/ + string port; + BaudRate baud_rate; + bool timestamps(false); + + try { + CmdLine cmd("This is a simple interface for reading/echoing from a serial port [115.2k,8N1].",' ',"0.1"); + ValueArg arg_port("p","port","Port to connect to",false,"/dev/ttyS0","string"); + ValueArg arg_baud("b","baud","Baud rate (9600,38400,115200) [115200]",false,"115200","string"); + SwitchArg switch_timestamps("t","timestamps","Print timestamps.",false); + + cmd.add(arg_port); + cmd.add(arg_baud); + cmd.add(switch_timestamps); + cmd.parse(argc,argv); + + port = arg_port.getValue(); + string baud = arg_baud.getValue(); + timestamps = switch_timestamps.getValue(); + + if ( baud == "9600" ) { + baud_rate = BaudRate_9600; + } else if ( baud == "38400" ) { + baud_rate = BaudRate_38400; + } else { + baud_rate = BaudRate_115200; + } + + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + } + try { + /****************************************** + ** Open + *******************************************/ + Serial serial(port,baud_rate,DataBits_8,StopBits_1,NoParity); + serial.block(5000); + Reader reader(&serial,timestamps); + Writer writer(&serial,timestamps); + + reader.wait(); + writer.wait(); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/process_statistics.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/process_statistics.cpp new file mode 100644 index 0000000..05f1b46 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/process_statistics.cpp @@ -0,0 +1,34 @@ +/** + * @file /src/utils/process_statistics.cpp + * + * @brief Detects parameter configurations for processes' on your system. + * + * This detects the availability and ranges of various process methods on + * your particular system. + * + * - Niceness + * - Real time priority range + * + * @date May, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + + std::cout << ecl::print_priority_diagnostics() << std::endl; + + std::cout << "This is very much a work in progress...." << std::endl; + + return 0; +} + + diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/quaternion2yaw.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/quaternion2yaw.cpp new file mode 100644 index 0000000..89e16c9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/quaternion2yaw.cpp @@ -0,0 +1,60 @@ +/** + * @file /src/utils/quaternion2yaw.cpp + * + * @brief Angle converter. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +/***************************************************************************** + * Using + ****************************************************************************/ + +using ecl::ArgException; +using ecl::CmdLine; +using ecl::UnlabeledValueArg; + +/***************************************************************************** +** Main program +*****************************************************************************/ +int main(int argc, char** argv) { + + /****************************************** + * Parse for the port name + ******************************************/ + double x, y, z, w; + + try { + CmdLine cmd("Calculator for yaw to quaternion.",' ',"0.1"); + UnlabeledValueArg arg_x("x","Quaternion component - x",true,0.0,"float", cmd); + UnlabeledValueArg arg_y("y","Quaternion component - y",true,0.0,"float", cmd); + UnlabeledValueArg arg_z("z","Quaternion component - z",true,0.0,"float", cmd); + UnlabeledValueArg arg_w("w","Quaternion component - w",true,0.0,"float", cmd); + cmd.parse(argc,argv); + x = arg_x.getValue(); + y = arg_y.getValue(); + z = arg_z.getValue(); + w = arg_w.getValue(); + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + return 1; + } + if ( ( x != 0.0 ) && ( y != 0.0 ) ) { + std::cout << "This quaternion has non-yaw components, aborting." << std::endl; + } + // This is a very naive way of calculating - it is only for the case where it is a + // rotation around a z-axis. + double rads = 2*acos(w)* ecl::sign(z); + double degrees = rads * 360.0 / (2 * ecl::pi); + std::cout << "Quaternion {x: " << x << " y: " << y << " z: " << z << " w: " << w << "} -> "; + std::cout << rads << " radians -> " << degrees << " degrees." << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/serial.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/serial.cpp new file mode 100644 index 0000000..2f3e021 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/serial.cpp @@ -0,0 +1,230 @@ +/** + * @file /src/utils/serial.cpp + * + * @brief Utility for testing a serial port connection. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace utils { + +/***************************************************************************** + * Using + ****************************************************************************/ + +using std::string; +using ecl::ArgException; +using ecl::CmdLine; +using ecl::SwitchArg; +using ecl::ValueArg; +using ecl::Serial; +using ecl::BaudRate; +using ecl::BaudRate_9600; +using ecl::BaudRate_38400; +using ecl::BaudRate_115200; +using ecl::DataBits_8; +using ecl::StopBits_1; +using ecl::NoParity; +using ecl::StandardException; +using ecl::Format; +using ecl::Dec; +using ecl::Hex; +using ecl::NoAlign; +using ecl::RightAlign; +using ecl::Thread; +using ecl::TimeStamp; +using ecl::MilliSleep; + +/***************************************************************************** + * Classes + ****************************************************************************/ + +class Writer +{ +public: + Writer(Serial *serial_device, bool timestamps = false) : + display_timestamps(timestamps), + serial(serial_device), + thread(&Writer::run,*this) + { (void) current_time; } + void wait() { thread.join(); } + +private: + bool display_timestamps; + long current_time; + TimeStamp timestamp; + Serial *serial; + Thread thread; + + void run() { + MilliSleep sleep; + string s; + char buffer[80]; + char *s_ptr; + + /****************************************** + ** Read + *******************************************/ + while (1) { + // Read a line from standard input + if ( fgets(buffer,80,stdin) == NULL ) { + break; + } + // fgets always terminates with a null character, even if it manages + // to read n-1 chars + s_ptr = buffer; + while ( *s_ptr != '\0') { ++s_ptr; } + serial->write(buffer,s_ptr - buffer); + if ( display_timestamps ) { + timestamp.stamp(); + std::cout << "[" << timestamp << "]" << std::endl; + } + sleep(5); + } + } +}; + +class Reader +{ +public: + Reader(Serial *serial_device, bool hexFormat = false, bool timestamps = false) : + serial(serial_device), + hex(hexFormat), + display_timestamps(timestamps), + format(6,RightAlign,Dec), + hex_format(-1,NoAlign,Hex), + thread(&Reader::run,*this) + { (void) current_time; } + + void wait() { thread.join(); } + +private: + void run() { + char s[255]; + unsigned long ch_read; + + if ( hex ) { std::cout << "Hex format" << std::endl; } else { std::cout << "Ascii format" << std::endl; } + + while (1) { + ch_read = serial->read(s,1); +// ch_read = serial->read(s,255); + if ( ch_read > 0 ) { + if ( display_timestamps ) { + time.stamp(); + std::cout << "[" << time << "] "; + } + for (unsigned int i = 0; i < ch_read; ++i) { + if ( hex ) { + std::cout << hex_format(s[i]) << " "; + } else { + std::cout << s[i]; + } + } + if ( hex ) { + std::cout << std::endl; + } else { + std::cout.flush(); + } + } else { +// std::cout << "Timed out." << std::endl; + } + } + } + Serial *serial; + bool hex; + bool display_timestamps; + long current_time; + TimeStamp time; + Format format; + Format hex_format; + Thread thread; + +}; + +} // namespace utils +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::utils; + +/***************************************************************************** +** Main program +*****************************************************************************/ +int main(int argc, char** argv) { + + /****************************************** + * Parse for the port name + ******************************************/ + string port; + BaudRate baud_rate; + bool hex(false); + bool timestamps(false); + + try { + CmdLine cmd("This is a simple interface for reading/echoing from a serial port [115.2k,8N1].",' ',"0.1"); + ValueArg arg_port("p","port","Port to connect to",false,"/dev/ttyS0","string"); + ValueArg arg_baud("b","baud","Baud rate (9600,38400,115200) [115200]",false,"115200","string"); + SwitchArg switch_hex("x","hex","Enable hex output.",false); + SwitchArg switch_timestamps("t","timestamps","Print timestamps.",false); + + cmd.add(arg_port); + cmd.add(arg_baud); + cmd.add(switch_hex); + cmd.add(switch_timestamps); + cmd.parse(argc,argv); + + port = arg_port.getValue(); + string baud = arg_baud.getValue(); + hex = switch_hex.getValue(); + timestamps = switch_timestamps.getValue(); + + if ( baud == "9600" ) { + baud_rate = BaudRate_9600; + } else if ( baud == "38400" ) { + baud_rate = BaudRate_38400; + } else { + baud_rate = BaudRate_115200; + } + + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + } + try { + /****************************************** + ** Open + *******************************************/ + Serial serial(port,baud_rate,DataBits_8,StopBits_1,NoParity); + serial.block(5000); + Reader reader(&serial,hex,timestamps); + Writer writer(&serial,timestamps); + + reader.wait(); + writer.wait(); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_client.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_client.cpp new file mode 100644 index 0000000..517b473 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_client.cpp @@ -0,0 +1,246 @@ +/** + * @file /src/utils/socket_client.cpp + * + * @brief Use to test tcp/ip connections. + * + * @date January 2010 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#ifdef ECL_IS_POSIX +#ifndef ECL_IS_MAC + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace demos { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::CmdLine; +using ecl::ValueArg; +using ecl::SwitchArg; +using ecl::ArgException; +using ecl::ConnectionHungUp; +using ecl::SocketClient; +using ecl::Format; +using ecl::Hex; +using ecl::NoAlign; +using ecl::Thread; +using ecl::MilliSleep; +using ecl::TimeStamp; + + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class Reader { +public: + Reader(SocketClient &socket_server, bool timestamps_reqd, bool hex_format_reqd = false) : + socket(socket_server), + timestamps(timestamps_reqd), + hex(hex_format_reqd), + new_line(true) + {} + + void loop() { + + Format hex_format(-1,NoAlign,Hex); + char c; + long ch_read; + MilliSleep sleep; + + if ( hex ) { std::cout << "Hex format" << std::endl; } else { std::cout << "Ascii format" << std::endl; } + + while (1) { + ch_read = socket.read(c); + if ( ch_read > 0 ) { + if ( hex ) { + if ( timestamps ) { + if ( new_line ) { timestamp.stamp(); } + std::cout << "[" << timestamp << "] : "; + } + std::cout << hex_format(c) << std::endl; + } else { + if ( timestamps && new_line ) { + timestamp.stamp(); + std::cout << "[" << timestamp << "] : "; + } + std::cout << c; + } + std::cout.flush(); + if ( timestamps ) { + if ( new_line ) { + new_line = false; + } else if ( c == '\n' ) { + new_line = true; + } + } + } else if ( ch_read < 0 ) { + if ( ch_read == ConnectionHungUp ) { + std::cout << "Server Hung Up." << std::endl; + break; + } + } else { + // nothing read + } + sleep(15); + } + + } + +private: + SocketClient &socket; + TimeStamp timestamp; + bool timestamps; + bool hex; + bool new_line; +}; + +class Writer { +public: + Writer(SocketClient &socket_server, bool timestamps_reqd) : socket(socket_server), timestamps(timestamps_reqd) {} + + void loop() { + MilliSleep sleep; + char buffer[256]; + memset(buffer,0,256); + char *s_ptr; + while( 1 ) { + if ( fgets(buffer,80,stdin) == NULL ) { + break; + } + // fgets always terminates with a null character, even if it manages + // to read n-1 chars + s_ptr = buffer; + while ( *s_ptr != '\0') { ++s_ptr; } + if ( timestamps ) { timestamp.stamp(); } + socket.write(buffer,s_ptr - buffer); + if ( timestamps ) { + std::cout << "[" << timestamp << "] : "; + } + std::cout << buffer; // already terminated by an endl; + std::cout.flush(); + sleep(500); + } + + } + +private: + SocketClient &socket; + TimeStamp timestamp; + bool timestamps; +}; + +} // namespace demos +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::demos; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char** argv) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Parsing Command Line" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + int port = 0; + string hostname; + bool hex(false); + bool timestamps(false); + + try { + CmdLine cmd("This is a simple interface for making a socket client connection.",' ',"0.1"); + ValueArg arg_hostname("n","hostname","Hostname of the server [localhost]",false,"localhost","string"); + ValueArg arg_port("p","port","Port number to connect to [1470].",false,1470,"integer"); + SwitchArg switch_timestamps("t","timestamp","Timestamp incoming/outgoings.",false); + SwitchArg switch_hex("x","hex","Enable hex output.",false); + + cmd.add(arg_hostname); + cmd.add(arg_port); + cmd.add(switch_hex); + cmd.add(switch_timestamps); + cmd.parse(argc,argv); + + hostname = arg_hostname.getValue(); + port = arg_port.getValue(); + hex = switch_hex.getValue(); + timestamps = switch_timestamps.getValue(); + + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + } + + std::cout << "Connecting to: " << hostname << " [" << port << "]" << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Read and Write Threads " << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + SocketClient client(hostname,port); + Writer writer(client,timestamps); + Reader reader(client,timestamps,hex); + Thread read_thread(&Reader::loop, reader); + Thread write_thread(&Writer::loop, writer); + + read_thread.join(); + write_thread.join(); + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_MAC */ + +#if !defined ECL_IS_POSIX || ECL_IS_MAC + +#include + +int main(int argc, char **argv) { + + std::cout << "This is a posix (not mac) only app." << std::endl; + return 0; +} + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_server.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_server.cpp new file mode 100644 index 0000000..4e03ab1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/socket_server.cpp @@ -0,0 +1,245 @@ +/** + * @file /src/utils/socket_server.cpp + * + * @brief Use to test tcp/ip connections. + * + * @date January 2010 + **/ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#ifdef ECL_IS_POSIX +#ifndef ECL_IS_MAC + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace demos { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::CmdLine; +using ecl::ValueArg; +using ecl::SwitchArg; +using ecl::ArgException; +using ecl::ConnectionHungUp; +using ecl::SocketServer; +using ecl::Format; +using ecl::Hex; +using ecl::NoAlign; +using ecl::Thread; +using ecl::MilliSleep; +using ecl::TimeStamp; + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class Reader { +public: + Reader(SocketServer &socket_server, bool timestamps_reqd, bool hex_format_reqd, const int &port_number) : + socket(socket_server), + timestamps(timestamps_reqd), + hex(hex_format_reqd), + port(port_number), + new_line(true) + { (void) port; } + + void loop() { + + Format hex_format(-1,NoAlign,Hex); + char c; + long ch_read; + MilliSleep sleep; + + if ( hex ) { std::cout << "Hex format" << std::endl; } else { std::cout << "Ascii format" << std::endl; } + + while (1) { + ch_read = socket.read(c); + if ( ch_read > 0 ) { + if ( hex ) { + if ( timestamps ) { + if ( new_line ) { timestamp.stamp(); } + std::cout << "[" << timestamp << "] : "; + } + std::cout << hex_format(c) << std::endl; + } else { + if ( timestamps && new_line ) { + timestamp.stamp(); + std::cout << "[" << timestamp << "] : "; + } + std::cout << c; + } + std::cout.flush(); + if ( timestamps ) { + if ( new_line ) { + new_line = false; + } else if ( c == '\n' ) { + new_line = true; + } + } + } else if ( ch_read < 0 ) { + if ( ch_read == ConnectionHungUp ) { + std::cout << "Client Hung Up." << std::endl; + exit(EXIT_FAILURE); + } + } else { + // nothing read + } + sleep(15); + } + + } + +private: + SocketServer &socket; + TimeStamp timestamp; + bool timestamps; + bool hex; + int port; + bool new_line; +}; + +class Writer { +public: + Writer(SocketServer &socket_server, bool timestamps_reqd) : + socket(socket_server), + timestamps(timestamps_reqd) + {} + + void loop() { + MilliSleep sleep; + char buffer[256]; + memset(buffer,0,256); + char *s_ptr; + while( 1 ) { + if ( fgets(buffer,80,stdin) == NULL ) { + break; + } + // fgets always terminates with a null character, even if it manages + // to read n-1 chars + s_ptr = buffer; + while ( *s_ptr != '\0') { ++s_ptr; } + if ( timestamps ) { timestamp.stamp(); } + socket.write(buffer,s_ptr - buffer); + if ( timestamps ) { + std::cout << "[" << timestamp << "] : "; + } + std::cout << buffer; // already terminated by an endl; + std::cout.flush(); + sleep(500); + } + + } + +private: + SocketServer &socket; + TimeStamp timestamp; + bool timestamps; +}; + +} // namespace demos +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::demos; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char** argv) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Parsing Command Line" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + int port = 0; + bool hex(false); + bool timestamps(false); + + try { + CmdLine cmd("This is a simple interface for making serving from a socket.",' ',"0.1"); + ValueArg arg_port("p","port","Port to connect to [1470].",false,1470,"integer"); + SwitchArg switch_hex("x","hex","Enable hex output.",false); + SwitchArg switch_timestamps("t","timestamp","Timestamp incoming/outgoings.",false); + + cmd.add(arg_port); + cmd.add(switch_hex); + cmd.add(switch_timestamps); + cmd.parse(argc,argv); + + hex = switch_hex.getValue(); + port = arg_port.getValue(); + timestamps = switch_timestamps.getValue(); + + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + } + + std::cout << "Listening on port: " << port << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Read and Write Threads " << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + SocketServer server(port); + server.listen(); + Writer writer(server,timestamps); + Reader reader(server,timestamps,hex,port); + Thread read_thread(&Reader::loop, reader); + Thread write_thread(&Writer::loop, writer); + + read_thread.join(); + write_thread.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_MAC */ + +#if !defined ECL_IS_POSIX || ECL_IS_MAC + +#include + +int main(int argc, char **argv) { + + std::cout << "This is a posix (not mac) only app." << std::endl; + return 0; +} + +#endif diff --git a/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/yaw2quaternion.cpp b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/yaw2quaternion.cpp new file mode 100644 index 0000000..b4a700e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_core_apps/src/utils/yaw2quaternion.cpp @@ -0,0 +1,46 @@ +/** + * @file /src/utils/yaw2quaternion.cpp + * + * @brief Angle converter. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** + * Using + ****************************************************************************/ + +using ecl::ArgException; +using ecl::CmdLine; +using ecl::UnlabeledValueArg; + +/***************************************************************************** +** Main program +*****************************************************************************/ +int main(int argc, char** argv) { + + /****************************************** + * Parse for the port name + ******************************************/ + double yaw = 0.0; + + try { + CmdLine cmd("Calculator for yaw to quaternion.",' ',"0.1"); + UnlabeledValueArg arg_yaw("yaw","Yaw angle to convert",true,0.0,"float", cmd); + cmd.parse(argc,argv); + yaw = arg_yaw.getValue(); + } catch ( ArgException &e ) { + std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; + } + Eigen::Quaternion q; + q = Eigen::AngleAxis(yaw, Eigen::Vector3d::UnitZ()); + std::cout << "Quaternion: [x: " << q.x() << " y: " << q.y() << " z: " << q.z() << " w: " << q.w() << "]" << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_devices/.cproject b/ros2_ws/src/ecl_core/ecl_devices/.cproject new file mode 100644 index 0000000..682ec2b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/.cproject @@ -0,0 +1,684 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + all + + true + + true + + true + + + + + + make + + clean + + true + + true + + true + + + + + + make + + test + + true + + true + + true + + + + + + make + + + + install + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_devices/.gitignore b/ros2_ws/src/ecl_core/ecl_devices/.gitignore new file mode 100644 index 0000000..b8137a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/.gitignore @@ -0,0 +1,4 @@ +# Test artifacts +odude.txt +odude2.txt +shared.txt diff --git a/ros2_ws/src/ecl_core/ecl_devices/.project b/ros2_ws/src/ecl_core/ecl_devices/.project new file mode 100644 index 0000000..d4facfc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/.project @@ -0,0 +1,78 @@ + + + ecl_devices + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_devices/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_devices/CHANGELOG.rst new file mode 100644 index 0000000..52fb22e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/CHANGELOG.rst @@ -0,0 +1,29 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +0.61.12 (2016-05-03) +-------------------- +* apple baud rate 460800 + +0.61.1 (2015-07-22) +------------------- +* catch the error code as a hint for when fcntl calls fail on serial devices +* additional baud rate enums for serial devices covering a wider range +* deprecated a couple of serial device baud rates that are no longer valid + +0.61.0 (2014-09-12) +------------------- +* allow immediate socket reuse in the socket client/server +* define an undefined baud rate for apple + +0.60.8 (2014-02-10) +------------------- +* control new posix.1-2008 SIGPIPE signals, `#34 `_ +* Contributors: Daniel Stonier + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_devices/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/CMakeLists.txt new file mode 100644 index 0000000..f15176c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/CMakeLists.txt @@ -0,0 +1,59 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_devices) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_containers REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_mpl REQUIRED) +find_package(ecl_threads REQUIRED) +find_package(ecl_type_traits REQUIRED) +find_package(ecl_utilities REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_containers + ecl_errors + ecl_mpl + ecl_threads + ecl_type_traits + ecl_utilities +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_devices/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_devices/doxygen/mainpage.dox new file mode 100644 index 0000000..8bacead --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/doxygen/mainpage.dox @@ -0,0 +1,178 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + +@section Introduction + + Devices provide a c++ interface (usually on top of a lower level + api such as posix) for input-output manipulation. + + It's pretty hard to find a library that treats devices in anything + but an ad-hoc way. There is no consistent interface. This attempts + to bring that to the subset of devices that control systems use. + It also allows hooking of streams to each and any of the devices. + + Also of interest, there are a few very theoretical approaches + to writing c++ devices. The ecl's first version too was along + these lines, but ultimately for control systems, being practical + wins over syntactic correctness. + + The devices here are kept as consistent and practical as possible + without sacrificing speed. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Device Classes + using ecl::OFile; + using ecl::SharedFile; + using ecl::Serial; + using ecl::OConsole; // Also IConsole, EConsole, but dont use directly, use console streams instead. + using ecl::String; // Dont use directly, use StringStream instead. + using ecl::SocketClient; // Simple and does ipv4 only. + using ecl::SocketServer; // Simple and does ipv4 only. + @endcode + + You will also need to link to -lecl_devices. + +@section DeviceUsage Device Usage + + @subsection openClose Open/Close + + All devices have both RAII and non-RAII setup methods. In practice, this means you either bundle all configuration + into the constructor, or you utilise the open() method to do configuration yourself. Usually RAII is the more ideal + approach, but sometimes its inconvenient so the latter method is also available. For example, the serial class: + + @code + Serial serial_raii("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // RAII + Serial serial_nonraii; + serial.open("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // non-RAII + @endcode + + Cleanup is always done in the destructor, though if you need to manually open/close a device frequently, a close() + method is also provided. + + @subsection readWrite Read/Write + + Some class are output devices (only write), others are input devices (only read) and some can do both. The read + and write modes will sometimes be configurable, (e.g. timeout or non-blocking for serial reads), however the + actual read and write operations will always be the same. + + @code + int n; + char buffer[256]; + n = source.read(buffer,256); + n = sink.write("dude\n",5); + @endcode + + @subsection Exceptions + + @subsection Concepts + + Essentially, a device class can be written in any way you please. + However, if you wish to connect it to higher level components, in particular, + streams, you must ensure you class satisfies certain device concepts. Refer to the + documentation in ecl_concepts for more information. + +@section Devices + + @subsection OFile + + - IO: write + - Seekable: no + - Sync/Async: synchronous + + This is the logger class. Since its primary purpose is to serve logging, the option to + make it seekable was dropped to keep it nice and simple. + + @sa @ref ecl::OFile "OFile". + + @subsection SharedFile + + - Status: DEPRACATED (can resurrect if needed) + - IO: write + - Seekable: no + - Sync/Async: synchronous. + + This is a multithreaded version of the SharedFile class. Multiple instances can open + the same file (uniquely identified by a string) and each contains its own buffer that is + utilised between flushing (this protects your output from getting tangled unnecessarily). + + @sa @ref ecl::SharedFile "SharedFile". + + @subsection Serial + + - IO: read/write + - Seekable: no + - Sync/Async: synchronous + + The most important thing to note with the serial class is that it really doesn't implement much of the underlying api. + Rather it wraps a configuration appropriate for control and keeps it as simple as possible. + + Of the possible read modes, it utilises only a timeout mode and a non-blocking mode. The other modes generally do not work + very well at the speed that control loops need to run. + + @sa @ref ecl::Serial "Serial", @ref ecl::BaudRate "BaudRate", @ref ecl::DataBits "DataBits", @ref ecl::StopBits "StopBits", @ref ecl::Parity "Parity". + + @subsection String + + - IO: read/write + - Seekable: no + - Sync/Async: synchronous + + This is a virtual device used for storing and converting strings (similar to Converters, but more general). + It is not intended for direct use, but as a mechanism for the stringstream class + which functions very similarly to the c++ stringstream classes. + + @sa @ref ecl::String "String". + + @subsection Sockets + + - IO: read/write + - Seekable: no + - Sync/Async: synchronous + + These are a very simple/rough implementation of ipv4. It isn't designed to be an industrial strength tool - just something for simple cross platform connections to enable quick and simple remote debugging program builds (or similar). + + Of the possible read modes, it utilises only a timeout mode and a non-blocking mode. The other modes generally do not work + very well at the speed that control loops need to run. + + @sa @ref ecl::SocketClient "SocketClient", @ref ecl::SocketServer "SocketServer". + +\section unitTests Unit Tests + + - src/test/files.cpp + - src/test/shared_files.cpp + +\section Examples + + - src/examples/serial_timeout.cpp : shows off the low latency timeout code [posix only]. + +\section utilities Utilities + + - ecl_core_apps/src/benchmarks/files.cpp + - ecl_core_apps/src/demos/socket_client.cpp + - ecl_core_apps/src/demos/socket_server.cpp + - ecl_core_apps/src/utils/hex.cpp : simple utility for reading/writing hex across the serial cable. + - ecl_core_apps/src/utils/serial.cpp : simple serial testing utility. + +\section ChangeLog + + - Apr 11 : Overhauled error handling. + - May 10 : Serial win32 implementation. + - May 10 : Cmake win32 framework. + - Jan 10 : A simple ipv4 @ref ecl::SocketServer "socket server". + - Jan 10 : A simple ipv4 @ref ecl::SocketClient "socket client". + - Dec 09 : A virtual @ref ecl::String "string" device. + - Nov 09 : Multi-threaded output to a @ref ecl::SharedFile "shared file" (aka thread-safe ofile). + - Nov 09 : @ref ecl::OConsole "OConsole" : also IConsole and EConsole for standard output handling. + - Sep 09 : Synchronised @ref ecl::OFile "output file" devices (posix). + - Sep 09 : An rs-232 @ref ecl::Serial "serial device" interface (posix). +*/ diff --git a/ros2_ws/src/ecl_core/ecl_devices/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_devices/doxygen/namespaces.dox new file mode 100644 index 0000000..31226af --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/doxygen/namespaces.dox @@ -0,0 +1,23 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::devices::tests + * + * @brief Frameworks created for the unit tests. + * + * Includes everything that was also added for compiling the unit tests. + **/ +/** + * @namespace ecl::interfaces + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. +**/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..7af9e37 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(devices) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices.hpp new file mode 100644 index 0000000..2cdc32d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices.hpp @@ -0,0 +1,28 @@ +/** + * @file /include/ecl/devices.hpp + * + * @brief Input/output devices. + * + * Classes related to input/output device manipulation. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_HPP_ +#define ECL_DEVICES_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "devices/modes.hpp" +#include "devices/traits.hpp" +#include "devices/ofile.hpp" +#include "devices/serial.hpp" +#include "devices/socket.hpp" +#include "devices/string.hpp" + +#endif /*ECL_IO_DEVICES_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/CMakeLists.txt new file mode 100644 index 0000000..155245b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(detail) + +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/devices) + diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/console.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/console.hpp new file mode 100644 index 0000000..431b103 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/console.hpp @@ -0,0 +1,296 @@ +/** + * @file /include/ecl/devices/console.hpp + * + * @brief Configures ecl devices for standard output/input. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_CONSOLE_HPP_ +#define ECL_DEVICES_CONSOLE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "detail/character_buffer.hpp" +#include "traits.hpp" +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [OConsole] +*****************************************************************************/ + +/** + * @brief Device for writing to standard output. + * + * Device for writing to standard output. It creates a wrapper class around + * the stdout handle from cstdio to implement an ecl output device. Do not + * use this directly, it serves only as the device handle for the console + * stream classes. + **/ +class ecl_devices_PUBLIC OConsole { +public: + /** + * @brief Default constructor. + */ + OConsole() : error_handler(NoError) {} + virtual ~OConsole() {} + + /********************* + ** Output Device API + **********************/ + /** + * @brief Dummy handle to satisfy the output device concept. + * + * For console devices this does nothing - the standard output is always + * open. It is just a dummy handle built to ensure the output device + * concept is satisfied. + * @return bool : always returns true (it is always open). + */ + bool open() { return true; } + + /** + * @brief Write a character to the buffer. + * + * Write a character to the buffer. It will automatically flush if the + * buffer exceeds its capacity. + * + * @param c : the character to write. + * @return long : the number of bytes written. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char &c); + /** + * @brief Write a character string to the buffer. + * + * Write a character string to the buffer. It will automatically flush if the + * buffer exceeds its capacity. + * + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long: the number of bytes written. + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + long write(const char* s, unsigned long n); + /** + * @brief Flush the internal buffer. + * + * Flushes the userspace buffers to standard output. + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + void flush(); + + /** + * @brief Returns the most recent error status. + * + * Use this to check on the status of the object after a method has been called. + * Mostly this is here to serve as a graceful fallback for when exceptions + * are disabled. + * @return + */ + const Error& error() const { return error_handler; } +private: + devices::CharStringBuffer buffer; + Error error_handler; +}; + +/***************************************************************************** +** Interface [EConsole] +*****************************************************************************/ + +/** + * @brief Device for writing o standard error. + * + * Device for writing to standard error. Do not + * use this directly, it serves only as the device handle for the console + * stream classes. + **/ +class ecl_devices_PUBLIC EConsole { +public: + /** + * @brief Default constructor. + */ + EConsole() : error_handler(NoError) {} + virtual ~EConsole() {} + + /********************* + ** Output Device API + **********************/ + /** + * @brief Dummy handle to satisfy the output device concept. + * + * For console devices this does nothing - the standard output is always + * open. It is just a dummy handle built to ensure the output device + * concept is satisfied. + * @return bool : always returns true (it is always open). + */ + bool open() { return true; } + + /** + * @brief Write a character to the buffer. + * + * Write a character to the buffer. It will automatically flush if the + * buffer exceeds its capacity. + * + * @param c : the character to write. + * @return long : the number of bytes written. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char &c); + /** + * @brief Write a character string to the buffer. + * + * Write a character string to the buffer. It will automatically flush if the + * buffer exceeds its capacity. + * + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long: the number of bytes written. + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + long write(const char* s, unsigned long n); + /** + * @brief Flush the internal buffer. + * + * Flushes the userspace buffers to standard output. + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + void flush(); + + /** + * @brief Returns the most recent error status. + * + * Use this to check on the status of the object after a method has been called. + * Mostly this is here to serve as a graceful fallback for when exceptions + * are disabled. + * @return + */ + const Error& error() const { return error_handler; } + +private: + devices::CharStringBuffer buffer; + Error error_handler; +}; + +/***************************************************************************** +** Interface [IConsole] +*****************************************************************************/ + +/** + * @brief Device for reading from standard output. + * + * Device for reading from standard output. It creates a wrapper class around + * the stdout handle from cstdio to implement an ecl output device. Do not + * use this directly, it serves only as the device handle for the console + * stream classes. + * + * One peculiarity of this device, is that it will strip newlines from the + * incoming input. This is a characteristic exclusive to the input console + * device because of its interactive nature with the user. + **/ +class ecl_devices_PUBLIC IConsole { +public: + /** + * @brief Default constructor. + */ + IConsole() : error_handler(NoError) {} + virtual ~IConsole() {} + /********************* + ** Input Device API + **********************/ + /** + * @brief Dummy handle to satisfy the input device concept. + * + * For console devices this does nothing - the standard input is always + * open. It is just a dummy handle built to ensure the input device + * concept is satisfied. + * @return bool : always returns true (it is always open). + */ + bool open() { return true; } + /** + * @brief Read a character from standard input. + * + * Reads a single character from standard input. + * + * @param c : character to read into from standard input. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char &c); + /** + * @brief Reads a character string from standard input. + * + * Reads a character string from standard input. + * + * @param s : character string to read into from standard input. + * @param n : the number of bytes to read. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char *s, const unsigned long &n); + +// long remaining() { +// long pos = ftell(stdin); // get current position marker. +// fseek(stdin,0,SEEK_END); // move pointer to the end of the file. +// long size = ftell(stdin); +// fseek(stdin,pos,SEEK_SET); +// +// return size; +// } + /** + * @brief Returns the most recent error status. + * + * Use this to check on the status of the object after a method has been called. + * Mostly this is here to serve as a graceful fallback for when exceptions + * are disabled. + * @return + */ + const Error& error() const { return error_handler; } +private: + Error error_handler; +}; + + +/***************************************************************************** +** Traits [Console] +*****************************************************************************/ +/** + * @brief Console source (input device) trait. + * + * Specialisation for the console source (input device) trait. + * + */ +template <> +class is_source : public True { + +}; + +/** + * @brief Console sink (output device) trait. + * + * Specialisation for the console sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +/** + * @brief Error console sink (output device) trait. + * + * Specialisation for the error console sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +} // namespace ecl + +#endif /* ECL_DEVICES_CONSOLE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/CMakeLists.txt new file mode 100644 index 0000000..303114e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/devices/detail) + diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/character_buffer.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/character_buffer.hpp new file mode 100644 index 0000000..7891fcf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/character_buffer.hpp @@ -0,0 +1,114 @@ +/** + * @file /include/ecl/devices/detail/character_buffer.hpp + * + * @brief A generic buffer for devices. + * + * @date September, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_BUFFER_HPP_ +#define ECL_DEVICES_BUFFER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Interface [CharBuffer] +*****************************************************************************/ +/** + * @brief Simple char string buffer class for use internally by the devices. + * + * This accommodates buffers which always reserve at least one extra + * byte for the end of string character. + * + * @sa @ref ecl::OConsole "OConsole". + */ +class CharBuffer { +public: + /********************* + ** Static Variables + **********************/ + static const unsigned int buffer_size = 4096; + + /********************* + ** C&D + **********************/ + CharBuffer() : fill_point_marker(0) {} + virtual ~CharBuffer() {} + + unsigned int remaining() { return ( buffer_size - fill_point_marker); } + unsigned int size() const { return fill_point_marker; } + bool full() const; + long append(const char &c); + long append(const char* s, unsigned long n); + void clear(); + char* c_ptr() { return contents; } + +private: + /********************* + ** Variables + **********************/ + unsigned int fill_point_marker; // Index pointing to where you would write the next char + char contents[buffer_size]; +}; + +/***************************************************************************** +** Interface [CharStringBuffer] +*****************************************************************************/ +/** + * @brief Simple char string buffer class for use internally by the devices. + * + * This accommodates buffers which always reserve at least one extra + * byte for the end of string character. + * + * @sa @ref ecl::OConsole "OConsole". + */ +class CharStringBuffer { +public: + /********************* + ** Static Variables + **********************/ + static const unsigned int buffer_size = 4095; // Array is actually this + 1 + + /********************* + ** C&D + **********************/ + CharStringBuffer() : fill_point_marker(0) { + contents[buffer_size] = '\0'; + } + + virtual ~CharStringBuffer() {} + + unsigned int remaining() { return ( buffer_size - fill_point_marker); } + bool full() const; + long append(const char &c); + long append(const char* s, unsigned long n); + const char* c_str(); + void clear(); + +private: + /********************* + ** Variables + **********************/ + unsigned int fill_point_marker; // Index pointing to where you would write the next char + char contents[buffer_size+1]; +}; + +} // namespace devices +} // namespace ecl + + +#endif /* ECL_DEVICES_BUFFER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/error_handler.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/error_handler.hpp new file mode 100644 index 0000000..8453bf6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/error_handler.hpp @@ -0,0 +1,68 @@ +/** + * @file /include/ecl/devices/detail/error_handler.hpp + * + * @brief Defines error handlers for posix devices. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_ERROR_HANDLER_HPP_ +#define ECL_DEVICES_ERROR_HANDLER_HPP_ + +/***************************************************************************** +** Cross Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Methods +*****************************************************************************/ + +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix open/fdopen calls. + */ +ecl::Error open_error(); +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix close/fclose calls. + */ +ecl::Error close_error(); +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix fsync calls. + */ +ecl::Error sync_error(); +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix write calls. + */ +ecl::Error write_error(); +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix read calls. + */ +ecl::Error read_error(); + +} // namespace devices +} // namespace ecl + +#endif /* ECL_DEVICES_ERROR_HANDLER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/exception_handler_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/exception_handler_pos.hpp new file mode 100644 index 0000000..500f60c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/exception_handler_pos.hpp @@ -0,0 +1,81 @@ +/** + * @file /include/ecl/devices/detail/exception_handler_pos.hpp + * + * @brief Defines exception handlers for posix devices. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_EXCEPTION_HANDLER_POS_HPP_ +#define ECL_DEVICES_EXCEPTION_HANDLER_POS_HPP_ + +/***************************************************************************** +** Cross Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Methods +*****************************************************************************/ + +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix open/fdopen calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param file_name : not directly used, but incorporated into the debugging message. + */ +StandardException open_exception(const char* loc, const std::string& file_name); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix close/fclose calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param file_name : not directly used, but incorporated into the debugging message. + */ +StandardException close_exception(const char* loc, const std::string& file_name); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix fsync calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param file_name : not directly used, but incorporated into the debugging message. + */ +StandardException sync_exception(const char* loc, const std::string& file_name); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix write calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +StandardException write_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix read calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +StandardException read_exception(const char* loc); + +} // namespace devices +} // namespace ecl + +#endif /* ECL_DEVICES_EXCEPTION_HANDLER_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_error_handler_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_error_handler_pos.hpp new file mode 100644 index 0000000..a0386f4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_error_handler_pos.hpp @@ -0,0 +1,214 @@ +/** + * @file /include/ecl/devices/detail/socket_error_handler_pos.hpp + * + * @brief Defines error handlers for posix sockets. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SOCKET_ERROR_HANDLER_POS_HPP_ +#define ECL_DEVICES_SOCKET_ERROR_HANDLER_POS_HPP_ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include // gethostbyname + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Methods +*****************************************************************************/ +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix socket calls. + * @return Error : the error type. + */ +inline ecl::Error socket_error() { + switch( errno ) { + case ( EACCES ) : return ecl::Error(ecl::OpenError); + case ( EAFNOSUPPORT): return ecl::Error(ecl::NotSupportedError); + case ( EINVAL ) : return ecl::Error(ecl::InvalidArgError); + case ( EMFILE ) : return ecl::Error(ecl::OutOfRangeError); + case ( ENFILE ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENOBUFS ) : return ecl::Error(ecl::MemoryError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( EPROTONOSUPPORT ) : return ecl::Error(ecl::NotSupportedError); + default : return ecl::Error(UnknownError); + } +} +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix bind calls. + * @return Error : the error type. + */ +inline ecl::Error bind_error() { + switch( errno ) { + case ( EACCES ) : return ecl::Error(ecl::PermissionsError); + case ( EADDRINUSE ) : return ecl::Error(ecl::BusyError); + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( EINVAL ) : return ecl::Error(ecl::BusyError); + case ( ENOTSOCK ) : return ecl::Error(ecl::InvalidObjectError); + case ( EADDRNOTAVAIL ) : return ecl::Error(ecl::InvalidObjectError); + case ( EFAULT ) : return ecl::Error(ecl::OutOfRangeError); + case ( ELOOP ) : return ecl::Error(ecl::SystemFailureError); + case ( ENAMETOOLONG ) : return ecl::Error(ecl::InvalidArgError); + case ( ENOENT ) : return ecl::Error(ecl::InvalidObjectError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( ENOTDIR ) : return ecl::Error(ecl::InvalidArgError); + case ( EROFS ) : return ecl::Error(ecl::PermissionsError); + default : return ecl::Error(UnknownError); + } +} +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix accept calls. + * @return Error : the error type. + */ +inline ecl::Error accept_error() { + switch( errno ) { + case ( EWOULDBLOCK ) : return ecl::Error(ecl::BlockingError); + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( ECONNABORTED ): return ecl::Error(ecl::InterruptedError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EINVAL ) : return ecl::Error(ecl::UsageError); + case ( EMFILE ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENFILE ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENOTSOCK ) : return ecl::Error(ecl::InvalidObjectError); + case ( EOPNOTSUPP ) : return ecl::Error(ecl::InvalidObjectError); + case ( EFAULT ) : return ecl::Error(ecl::PermissionsError); + case ( ENOBUFS ) : return ecl::Error(ecl::MemoryError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( EPROTO ) : return ecl::Error(ecl::InvalidArgError); + case ( EPERM ) : return ecl::Error(ecl::PermissionsError); + default : return ecl::Error(UnknownError); + } +} +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix recv calls. + * @return Error : the error type. + */ +inline ecl::Error receive_error() { + + switch( errno ) { + case ( EAGAIN || EWOULDBLOCK ) : return ecl::Error(ecl::InterruptedError); + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( ECONNREFUSED) : return ecl::Error(ecl::ConnectionError); + case ( EFAULT ) : return ecl::Error(ecl::SystemFailureError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EINVAL ) : return ecl::Error(ecl::InvalidArgError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( ENOTCONN ) : return ecl::Error(ecl::ConnectionError); + case ( ENOTSOCK ) : return ecl::Error(ecl::InvalidObjectError); + default : return ecl::Error(UnknownError); + } +} +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix ioctl calls. + * @return Error : the error type. + */ +inline ecl::Error ioctl_error() { + + switch( errno ) { + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( EFAULT ) : return ecl::Error(ecl::OutOfRangeError); + case ( EINVAL ) : return ecl::Error(ecl::InvalidArgError); + case ( ENOTTY ) : return ecl::Error(ecl::InvalidObjectError); + default : return ecl::Error(UnknownError); +} +} + +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix send calls. + * @return Error : the error type. + */ +inline ecl::Error send_error() { + + switch( errno ) { + case ( EAGAIN || EWOULDBLOCK ) : return ecl::Error(ecl::BlockingError); + case ( EWOULDBLOCK ) : return ecl::Error(ecl::BlockingError); + case ( EACCES ) : return ecl::Error(ecl::PermissionsError); + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( ECONNRESET ) : return ecl::Error(ecl::InterruptedError); + case ( EFAULT ) : return ecl::Error(ecl::SystemFailureError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EINVAL ) : return ecl::Error(ecl::InvalidArgError); + case ( EISCONN ) : return ecl::Error(ecl::ConnectionError); + case ( EMSGSIZE ) : return ecl::Error(ecl::WriteError); + case ( ENOBUFS ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( ENOTCONN ) : return ecl::Error(ecl::ConnectionError); + case ( ENOTSOCK ) : return ecl::Error(ecl::InvalidObjectError); + case ( EOPNOTSUPP ) : return ecl::Error(ecl::NotSupportedError); + case ( EPIPE ) : return ecl::Error(ecl::InterruptedError); + default : return ecl::Error(UnknownError); +} +} + +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix gethostbyname calls. + * @return Error : the error type. + */ +inline ecl::Error gethostbyname_error() { + switch( h_errno ) { + case ( HOST_NOT_FOUND ) : return ecl::Error(ecl::ConnectionError); + case ( NO_ADDRESS ) : return ecl::Error(ecl::InvalidArgError); + case ( NO_RECOVERY ) : return ecl::Error(ecl::UnknownError); + default : return ecl::Error(ecl::UnknownError); + } +} +/** + * This function generates a custom ecl::Error response + * for posix error numbers generated by posix connect calls. + * @return Error : the error type. + */ +inline ecl::Error connection_error() { + switch( errno ) { + case ( ( EACCES ) || ( EPERM ) ): return ecl::Error(ecl::PermissionsError); + case ( EADDRINUSE ) : return ecl::Error(ecl::BusyError); + case ( EAFNOSUPPORT ): return ecl::Error(ecl::NotSupportedError); + case ( EAGAIN ) : return ecl::Error(ecl::OutOfResourcesError); + case ( EALREADY ) : return ecl::Error(ecl::BlockingError); + case ( EBADF ) : return ecl::Error(ecl::InvalidObjectError); + case ( ECONNREFUSED ): return ecl::Error(ecl::ConnectionRefusedError); + case ( EFAULT ) : return ecl::Error(ecl::OutOfRangeError); + case ( EINPROGRESS ) : return ecl::Error(ecl::BlockingError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EISCONN ) : return ecl::Error(ecl::ConnectionError); + case ( ENETUNREACH ) : return ecl::Error(ecl::ConfigurationError); + case ( ENOTSOCK ) : return ecl::Error(ecl::InvalidObjectError); + case ( ETIMEDOUT ) : return ecl::Error(ecl::TimeOutError); + default : return ecl::Error(ecl::UnknownError); + } +} + +} // namespace devices +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ +#endif /* ECL_DEVICES_SOCKET_ERROR_HANDLER_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_exception_handler_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_exception_handler_pos.hpp new file mode 100644 index 0000000..4823849 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/detail/socket_exception_handler_pos.hpp @@ -0,0 +1,112 @@ +/** + * @file /include/ecl/devices/detail/socket_exception_handler_pos.hpp + * + * @brief Defines exception handlers for posix sockets. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SOCKET_EXCEPTION_HANDLER_POS_HPP_ +#define ECL_DEVICES_SOCKET_EXCEPTION_HANDLER_POS_HPP_ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Methods +*****************************************************************************/ + +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix socket calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException socket_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix bind calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException bind_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix accept calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException accept_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix receive calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException receive_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix ioctl calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException ioctl_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix send calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +ecl::StandardException send_exception(const char* loc); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix gethostbyname calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param hostname : name of the server's host. + * @return StandardException : the exception type. + */ +StandardException gethostbyname_exception(const char* loc, const std::string& hostname); +/** + * This function generates a custom StandardException response + * for posix error numbers generated by posix connect calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @return StandardException : the exception type. + */ +StandardException connection_exception(const char* loc); + +} // namespace devices +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ +#endif /* ECL_DEVICES_SOCKET_EXCEPTION_HANDLER_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/macros.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/macros.hpp new file mode 100644 index 0000000..a0e3a37 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/devices/macros.hpp + * + * @brief Macros for ecl devices. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_MACROS_HPP_ +#define ECL_DEVICES_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_devices_EXPORTS // we are building a shared lib/dll + #define ecl_devices_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_devices_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_devices_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_devices_PUBLIC + #define ecl_devices_LOCAL +#endif + +#endif /* ECL_DEVICES_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/modes.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/modes.hpp new file mode 100644 index 0000000..12db3df --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/modes.hpp @@ -0,0 +1,43 @@ +/** + * @file /include/ecl/devices/modes.hpp + * + * @brief Device modes. + * + * @date October, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_MODES_HPP_ +#define ECL_DEVICES_MODES_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +/** + * @brief Write mode for devices. + * + * Defines the write modes for writing to an output device. Primarily used for + * files. + **/ +enum WriteMode { + New, /**< @brief Opens a new object (deletes existing objects). **/ + Append /**< @brief Appends to an existing object (opens if not existing). **/ +}; + + +} // namespace ecl + +#endif /* ECL_DEVICES_MODES_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile.hpp new file mode 100644 index 0000000..e2944d2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile.hpp @@ -0,0 +1,32 @@ +/** + * @file /include/ecl/devices/ofile.hpp + * + * @brief Synchronous and asynchronous file io. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_OFILE_HPP_ +#define ECL_DEVICES_OFILE_HPP_ + +/************************************************************************* + * Includes + ************************************************************************/ + +#include + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #include "ofile_pos.hpp" +#elif defined(ECL_IS_WIN32) + #include "ofile_w32.hpp" +#endif + + +#endif /* ECL_DEVICES_OFILE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_pos.hpp new file mode 100644 index 0000000..d24211e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_pos.hpp @@ -0,0 +1,343 @@ +/** + * @file /include/ecl/devices/ofile_pos.hpp + * + * @brief Posix interface for synchronous file io. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_OFILE_POS_HPP_ +#define ECL_DEVICES_OFILE_POS_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include // FILE calls +#include +#include +#include +#include +#include "detail/exception_handler_pos.hpp" +#include "modes.hpp" +#include "traits.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Output File] +*****************************************************************************/ +/** + * @brief The standard output file device for the ecl. + * + * This device uses the underlying posix FILE streams for synchronised + * file output using the usual write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the class automatically does the cleanup for you in the destructor. + * + * This is the class to use as your standard, generic logger. + * + * Usage: + * + * The serial device does both input and output, using the usual read/write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the serial class does the cleanup for you in the destructor. + * + * Files can be opened either as new files or to be appended to using the + * appropriate enum + * + * @code + * File file_raii("raii.txt",New); // RAII + * File file_nonraii; + * file_nonraii.open("nonraii.txt",Append); // non-RAII + * @endcode + * + * Writing: + * + * @code + * file.write("Dude\n",5); + * @endcode + * + * Performance: + * + * Run the bench_files.cpp for a comparison of different techniques. It is + * definitely faster than both standard posix open/close because it makes + * use of system buffers, and the c++ ifstreams (these are really slow). + * + * Error Handling: + * + * OFile provides detailed error messages via exceptions. Note that + * everything but open() throws exceptions in debug mode only (for + * performance reasons). + * + * If exceptions are disabled, check the result of each function call + * (usually a boolean or a check for '-1') and then ascertain the + * last error via the error() method. + * + * @sa @ref WriteMode "WriteMode". + */ +class OFile { +public: + /********************* + ** C&D + **********************/ + /** + * @brief Non-RAII style constructor, doesn't open a file. + * + * Sometimes its more convenient to open manually rather than inside + * constructors. Use this with the open() command to do so. You can + * check for open status via the isOpen accessor. + */ + OFile(); + /** + * @brief Opens a file for writing, RAII style. + * + * Accepts the filename, write mode (New or Append) and attempts to open + * the file for writing. It will throw an exception if the open attempt fails. + * Refer to open() for more details. + * + * @param file_name : name of the file to open. + * @param mode : mode of writing, either New or Append. + * + * @exception StandardException : throws if the connection failed to open. + */ + OFile(const std::string &file_name, const WriteMode &mode = New); + + /** + * @brief Synchronises the file buffers with the hard disk and cleans up. + */ + virtual ~OFile(); + + /********************* + ** Open/Close + **********************/ + /** + * @brief Status flag indicating if the file is open/closed. + * + * @return bool : true if open, false otherwise. + */ + virtual bool open() { return ( file != NULL ) ? true : false; } + + /** + * @brief Opens the file for writing. + * + * Configures and opens the file for writing in either New or Append mode. + * Note, that you don't need to do this if you constructed this class with the RAII + * style constructor as it gets automatically called. + * + * This function will either throw, or return false and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - InvalidArgError + * - PermissionsError + * - OutOfResourcesError + * - InterruptedError + * - MemoryError + * - UsageError + * - SystemFailureError + * - InvalidObjectError + * + * @sa devices::open_error, devices::open_exception + * + * @param file_name : name of the file to open. + * @param mode : mode of writing, either New or Append. + * @return success or failure (check error()) of the opening. + * + * @exception StandardException : throws if the connection failed to open. + */ + virtual bool open(const std::string &file_name, const WriteMode &mode = New); + + /** + * @brief Closes the file. + * + * The destructor automatically handles this, so in most cases its redundant. + * However there are times when a file must be manually closed. + * + * This function will either throw, or return false and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - InvalidArgError + * - SystemFailureError, + * - InterruptedError + * + * @sa devices::close_error, devices::close_exception + * + * @exception StandardException : throws if closing/cleaning up failed. + */ + virtual bool close(); + + /********************* + ** Utility Methods + **********************/ + /** + * @brief The name of the output file. + * @return string : the file name. + */ + virtual const std::string& filename() const { return name; } + + + /********************* + ** Output Methods + **********************/ + /** + * @brief Write a character to the file buffer. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param c : the character to write. + * @return long: the number of bytes written (-1 on error). + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + virtual long write(const char &c); + /** + * @brief Write a character string to the buffer. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long: the number of bytes written (-1 on error). + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char* s, unsigned long n); + + /** + * @brief Write a byte array to the buffer. + * + * This is the preferred way to write as it avoids char pointers. This + * works for both signed and unsigned char types and the size to write + * is referenced from the container's size. Ecl stencils are a good fit + * for this api. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param byte_array : the byte array to write to the file. + * @return long: the number of bytes written (-1 on error). + * @tparam ByteArray : a container of bytes satisfying the ByteContainer Concept (see ecl_concepts). + * + */ + template + long write(const ByteArray &byte_array); + /** + * @brief Flush the internal buffer. + * + * Flushes the userspace buffers to kernel/disk. + * + * This function will either throw, or return false and set the error() flag + * to UnknownError (the underlying fflush function isn't very verbose) + * if exceptions are disabled. + * + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + virtual bool flush(); + + /** + * @brief Reports on the error state of the last operation. + */ + const Error& error() const { return error_handler; } + +private: + /********************* + ** Variables + **********************/ + int file_descriptor; + FILE *file; + std::string name; + Error error_handler; +}; + +/***************************************************************************** +** Template Implementation +*****************************************************************************/ + +template +long OFile::write(const ByteArray&byte_array) { + + ecl_compile_time_concept_check(ecl::ByteContainerConcept); + if ( !open() ) { + ecl_debug_throw(ecl::StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(&byte_array[0],byte_array.size(),1,file); + if ( written == 0) { + ecl_debug_throw(ecl::StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + return byte_array.size()*written; // fwrite returns the number of 'items' written, not bytes! +} + + +/***************************************************************************** +** Traits [OFile] +*****************************************************************************/ + +/** + * @brief File sink (output device) trait. + * + * Specialisation for the file sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +} // namespace ecl + + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_DEVICES_OFILE_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_w32.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_w32.hpp new file mode 100644 index 0000000..463eaea --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/ofile_w32.hpp @@ -0,0 +1,343 @@ +/** + * @file /include/ecl/devices/ofile_w32.hpp + * + * @brief Win32 interface for synchronous file io. + * + * @date April 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_OFILE_W32_HPP_ +#define ECL_DEVICES_OFILE_W32_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include // FILE calls +#include +#include +#include +#include +#include "detail/exception_handler_pos.hpp" +#include "modes.hpp" +#include "traits.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Output File] +*****************************************************************************/ +/** + * @brief The standard output file device for the ecl. + * + * This device uses the underlying win32 FILE streams for synchronised + * file output using the usual write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the class automatically does the cleanup for you in the destructor. + * + * This is the class to use as your standard, generic logger. + * + * Usage: + * + * The serial device does both input and output, using the usual read/write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the serial class does the cleanup for you in the destructor. + * + * Files can be opened either as new files or to be appended to using the + * appropriate enum + * + * @code + * File file_raii("raii.txt",New); // RAII + * File file_nonraii; + * file_nonraii.open("nonraii.txt",Append); // non-RAII + * @endcode + * + * Writing: + * + * @code + * file.write("Dude\n",5); + * @endcode + * + * Performance: + * + * Run the bench_files.cpp for a comparison of different techniques. It is + * definitely faster than both standard posix open/close because it makes + * use of system buffers, and the c++ ifstreams (these are really slow). + * + * Error Handling: + * + * OFile provides detailed error messages via exceptions. Note that + * everything but open() throws exceptions in debug mode only (for + * performance reasons). + * + * If exceptions are disabled, check the result of each function call + * (usually a boolean or a check for '-1') and then ascertain the + * last error via the error() method. + * + * @sa @ref WriteMode "WriteMode". + */ +class ecl_devices_PUBLIC OFile { +public: + /********************* + ** C&D + **********************/ + /** + * @brief Non-RAII style constructor, doesn't open a file. + * + * Sometimes its more convenient to open manually rather than inside + * constructors. Use this with the open() command to do so. You can + * check for open status via the isOpen accessor. + */ + OFile(); + /** + * @brief Opens a file for writing, RAII style. + * + * Accepts the filename, write mode (New or Append) and attempts to open + * the file for writing. It will throw an exception if the open attempt fails. + * Refer to open() for more details. + * + * @param file_name : name of the file to open. + * @param mode : mode of writing, either New or Append. + * + * @exception StandardException : throws if the connection failed to open. + */ + OFile(const std::string &file_name, const WriteMode &mode = New); + + /** + * @brief Synchronises the file buffers with the hard disk and cleans up. + */ + virtual ~OFile(); + + /********************* + ** Open/Close + **********************/ + /** + * @brief Status flag indicating if the file is open/closed. + * + * @return bool : true if open, false otherwise. + */ + virtual bool open() { return ( file != NULL ) ? true : false; } + + /** + * @brief Opens the file for writing. + * + * Configures and opens the file for writing in either New or Append mode. + * Note, that you don't need to do this if you constructed this class with the RAII + * style constructor as it gets automatically called. + * + * This function will either throw, or return false and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - InvalidArgError + * - PermissionsError + * - OutOfResourcesError + * - InterruptedError + * - MemoryError + * - UsageError + * - SystemFailureError + * - InvalidObjectError + * + * @sa devices::open_error, devices::open_exception + * + * @param file_name : name of the file to open. + * @param mode : mode of writing, either New or Append. + * @return success or failure (check error()) of the opening. + * + * @exception StandardException : throws if the connection failed to open. + */ + virtual bool open(const std::string &file_name, const WriteMode &mode = New); + + /** + * @brief Closes the file. + * + * The destructor automatically handles this, so in most cases its redundant. + * However there are times when a file must be manually closed. + * + * This function will either throw, or return false and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - InvalidArgError + * - SystemFailureError, + * - InterruptedError + * + * @sa devices::close_error, devices::close_exception + * + * @exception StandardException : throws if closing/cleaning up failed. + */ + virtual bool close(); + + /********************* + ** Utility Methods + **********************/ + /** + * @brief The name of the output file. + * @return string : the file name. + */ + virtual const std::string& filename() const { return name; } + + + /********************* + ** Output Methods + **********************/ + /** + * @brief Write a character to the file buffer. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param c : the character to write. + * @return long: the number of bytes written (-1 on error). + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + virtual long write(const char &c); + /** + * @brief Write a character string to the buffer. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long: the number of bytes written (-1 on error). + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char* s, unsigned long n); + + /** + * @brief Write a byte array to the buffer. + * + * This is the preferred way to write as it avoids char pointers. This + * works for both signed and unsigned char types and the size to write + * is referenced from the container's size. Ecl stencils are a good fit + * for this api. + * + * This function will either throw, or return -1 and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - BlockingError + * - PermissionsError + * - OutOfRangeError + * - MemoryError + * - OutOfResourcesError + * - SystemFailureError + * - InterruptedError + * - InvalidObjectError + * + * @sa devices::write_error, devices::write_exception + * + * @param byte_array : the byte array to write to the file. + * @return long: the number of bytes written (-1 on error). + * @tparam ByteArray : a container of bytes satisfying the ByteContainer Concept (see ecl_concepts). + * + */ + template + long write(const ByteArray &byte_array); + /** + * @brief Flush the internal buffer. + * + * Flushes the userspace buffers to kernel/disk. + * + * This function will either throw, or return false and set the error() flag + * to UnknownError (the underlying fflush function isn't very verbose) + * if exceptions are disabled. + * + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + virtual bool flush(); + + /** + * @brief Reports on the error state of the last operation. + */ + const Error& error() const { return error_handler; } + +private: + /********************* + ** Variables + **********************/ + int file_descriptor; + FILE *file; + std::string name; + Error error_handler; +}; + +/***************************************************************************** +** Template Implementation +*****************************************************************************/ + +template +long OFile::write(const ByteArray&byte_array) { + + ecl_compile_time_concept_check(ecl::ByteContainerConcept); + if ( !open() ) { + ecl_debug_throw(ecl::StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(&byte_array[0],byte_array.size(),1,file); + if ( written == 0) { + ecl_debug_throw(ecl::StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + return byte_array.size()*written; // fwrite returns the number of 'items' written, not bytes! +} + + +/***************************************************************************** +** Traits [OFile] +*****************************************************************************/ + +/** + * @brief File sink (output device) trait. + * + * Specialisation for the file sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +} // namespace ecl + + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_DEVICES_OFILE_W32_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial.hpp new file mode 100644 index 0000000..fb2a9e4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial.hpp @@ -0,0 +1,33 @@ +/** + * @file /include/ecl/devices/serial.hpp + * + * @brief Serial (RS232) interfaces. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SERIAL_HPP_ +#define ECL_DEVICES_SERIAL_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "serial_parameters.hpp" +#if defined(ECL_IS_POSIX) + #include "serial_pos.hpp" +#elif defined(ECL_IS_WIN32) + #include "serial_w32.hpp" +#endif + +#endif /* ECL_DEVICES_SERIAL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_parameters.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_parameters.hpp new file mode 100644 index 0000000..a6d7131 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_parameters.hpp @@ -0,0 +1,87 @@ +/** + * @file /include/ecl/devices/serial_parameters.hpp + * + * @brief Cross-platform abstractions for the serial class. + * + * @date September 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SERIAL_PARAMETERS_HPP_ +#define ECL_DEVICES_SERIAL_PARAMETERS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Enums +*****************************************************************************/ + +/** + * @brief Serial connection baud rate. + * + * The baud rate of a serial connection. Support is rather dependent on the + * device, so check first. Some good references: + * + * - National Instruments : http://digital.ni.com/public.nsf/allkb/D37754FFA24F7C3F86256706005B9BE7 + * - FTDI : http://www.ftdichip.com/Support/Documents/AppNotes/AN232B-05_BaudRates.pdf + **/ +enum BaudRate { + BaudRate_110, // these are supported by most serial devices + BaudRate_300, + BaudRate_600, + BaudRate_1200, + BaudRate_2400, + BaudRate_4800, + BaudRate_9600, + BaudRate_19200, + BaudRate_38400, + BaudRate_57600, + BaudRate_115200, + BaudRate_230400, + BaudRate_460800, + BaudRate_921600 +}; + +/** + * @brief Data bits used in a serial packet. + * + * The number of data bits used in the serial protocol. + **/ +enum DataBits { + DataBits_5 = 0, + DataBits_6, + DataBits_7, + DataBits_8, +}; + +/** + * @brief Stop bits used in a serial packet. + * + * Number of stop bits used in the serial protocol. + **/ +enum StopBits { + StopBits_1 = 0, + StopBits_15, + StopBits_2 +}; + +/** + * @brief Parity of the serial packet. + * + * Parity of the serial communication. + **/ +enum Parity { + NoParity = 0, + OddParity = 1, + EvenParity = 2 +}; + +} // namespace ecl + +#endif /* ECL_DEVICES_SERIAL_PARAMETERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_pos.hpp new file mode 100644 index 0000000..a3c0dd5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_pos.hpp @@ -0,0 +1,552 @@ +/** + * @file /include/ecl/devices/serial_pos.hpp + * + * @brief Posix interface for serial (RS232) devices. + * + * @date September 2009 + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_DEVICES_SERIAL_POS_HPP_ +#define ECL_DEVICES_SERIAL_POS_HPP_ + +/***************************************************************************** + ** Platform Check + *****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "detail/error_handler.hpp" +#include "detail/exception_handler_pos.hpp" +#include "serial_parameters.hpp" +#include "traits.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + + /***************************************************************************** + ** Interface [Serial] + *****************************************************************************/ + /** + * @brief Posix implementation for a serial (RS232) device. + * + * This device is a c++ wrapper around the posix termios functions. It + * configures the serial device as a non-seekable source-sink (read-write), + * device. + * + * Just a quick note about the serial termios functions. They can + * be configured in a variety of ways for a variety of + * situations (modems, terminals, login consoles). Most of these are + * redundant for control, so we just keep it simple here + * and use a simple wrapper around a useful configuration for + * control. This keeps + * options and settings to a minimum and lets us get on with the job + * of control. + * + * Read Modes + * + * In posix, there are several available read modes. As mentioned above, + * some of these are for all intents and purposes, redundant for control. + * One particular example is the message + * buffering configuration that uses both a packet size limit as well + * as an inter-byte timeout when reading. Unfortunately the minimum inter-byte + * timeout is a massive 200ms, which makes it all but useless for + * control. + * + * Subsequently, the default mode of operation is using + * a timeout - as this one will automatically return you whenever any + * new data comes in. Great for control! An alternative non-blocking option is + * also provided. + * + * Usage: + * + * The serial device does both input and output, using the usual read/write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the serial class does the cleanup for you in the destructor. + * + * Protocol configuration is done either in the constructor or the open() + * command by passing a port name and a set of enumerated + * protocol configuration parameters - @ref BaudRate "baud rate", + * @ref DataBits "data bits", @ref StopBits "stop bits", + * and @ref Parity "parity" are defined via enums. + * + * @code + * Serial serial_raii("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // RAII + * Serial serial_nonraii; + * serial_nonraii.open("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // non-RAII + * @endcode + * + * Reading with various timeouts. + * + * @code + * int n; + * unsigned char buffer[256]; + * serial.block(500); // timeout of 500ms + * n = serial.read(buffer,256); + * serial.unblock(); + * n = serial.read(buffer,256); // always returns, even if nothing is there. + * @endcode + * + * Writing: + * + * @code + * serial.write("Dude\n",5); + * @endcode + * + * Concepts: + * + * The serial device handles reading and writing for all byte types, so it + * supports both the InputOutputCharDevice and InputOutputByteDevice concepts + * (refer to ecl_concepts). + * + * Notes on Serial Port Configuration: + * + * It's configuration is customised for robot control type devices. Given + * the variation in configuration that can be set for serial devices, a list + * of assumptions about the device is given below: + * + * - it is locked for the one process, if already locked it will throw. + * - flow control is disabled. + * - starts in blocking mode with timeouts, but can be switched. + * - buffers are cleared on opening. + */ + class Serial + { + public: + /********************* + ** C&D + **********************/ + /** + * @brief Non-RAII style constructor, doesn't make a connection. + * + * Sometimes its more convenient to open manually rather than inside + * constructors. Use this with the open() command to do so. You can + * check for open status with via the open accessor. + */ + Serial() : is_open(false), error_handler(NoError) + {}; + /** + * @brief Constructs and opens the connection, RAII style. + * + * Configures and opens the serial device (RAII style) with the specified + * parameters. + * + * By default, the port is configured to read in blocking mode + * (with overly large timeout of 5s) - use the block(timeout_ms) and unblock() + * methods to alter its behaviour. + * + * @param port_name : the device name. + * @param baud_rate : baud rate. + * @param data_bits : the number of bits in a single message byte. + * @param stop_bits : the number of bits after the data used for error checking. + * @param parity : the parity used for checksums. + * @exception StandardException : throws if the connection failed to open. + */ + Serial(const std::string& port_name, const BaudRate &baud_rate = BaudRate_115200, const DataBits &data_bits = DataBits_8, + const StopBits &stop_bits = StopBits_1, const Parity &parity = NoParity ); + + /** + * @brief Cleans up the file descriptor. + * + * Cleans up the file descriptor. + */ + virtual ~Serial(); + + /********************* + ** Open/Close + **********************/ + /** + * @brief Opens the connection. + * + * Configures and opens the serial device with the specified + * parameters. You don't need to do this if you constructed this class with the RAII + * style constructor. + * + * If the device is already open, it will first close and then reopen the device. + * + * This function will either throw, or return false and set the error() flag + * if exceptions are disabled. Error flag values for this function include: + * + * - InvalidArgError + * - PermissionsError + * - OutOfResourcesError + * - InterruptedError + * - MemoryError + * - UsageError + * - SystemFailureError + * - InvalidObjectError + * - IsLockedError + * + * If successful, it will configure the port with a blocking policy and a + * timeout of 5s. Use the block() method after opening to alter the behaviour. + * + * @sa devices::open_error, devices::open_exception + * + * @param port_name : the device name. + * @param baud_rate : baud rate. + * @param data_bits : the number of bits in a single message byte. + * @param stop_bits : the number of bits after the data used for error checking. + * @param parity : the parity used for checksums. + * @exception StandardException : throws if the connection failed to open. + */ + bool open(const std::string& port_name, const BaudRate &baud_rate = BaudRate_115200, const DataBits &data_bits = DataBits_8, + const StopBits &stop_bits = StopBits_1, const Parity &parity = NoParity ); + + /** + * @brief Closes the port connection. + * + * The destructor automatically handles this, so in most cases its redundant. + * However there are times when a serial port must be temporarily closed. + * This enables you to do that. + */ + void close(); + /** + * @brief Status flag indicating if the serial port is open/closed. + * + * True if the serial port is open and connected, false otherwise. + * This goes beyond just maintaining some internal state, it will also + * check if the device file (e.g. /dev/ttyUSB0) is still available and + * has access permissions for the user. If it's not, it will automatically + * close the serial device. + */ + bool open(); + + /********************* + ** Writing + **********************/ + /** + * @brief Write a character to the serial port. + * + * This function gives a compile time error if the type is not a byte (refer to ecl_mpl's) + * is_byte type traits. + * + * @param byte : the character to write. + * @exception StandardException : throws reading returned an error [debug mode only]. + **/ + template + long write(const Byte &byte); + + /** + * @brief Write a character string to the serial port. + * + * This function gives a compile time error if the type is not a byte (refer to ecl_mpl's) + * is_byte type traits. + * + * @param bytes : points to the beginning of the character string. + * @param n : the number of characters to write. + * @exception StandardException : throws reading returned an error [debug mode only]. + **/ + template + long write(const Byte *bytes, const unsigned long &n); + + /** + * @brief A dummy flush function, not used, but needed by streams. + * + * This is unused - but is included so as to implement streaming functionality + * on top of this device. + */ + void flush() + {} + + /********************* + ** Reading Modes + **********************/ + /** + * @brief Switch to blocking mode with a timeout for reading. + * + * Switched to blocking mode with the specified timeout in milliseconds. + * Note that there is a valid minimum value set by termios for serial + * timeouts - 100ms. We go beyond this though - if a timeout < 100ms is set + * this serial class will implement its own blocking loop with the specified + * timeout. If the timeout is > 100ms, then it will default to typical termios + * behaviour. + * + * Low latency blocking has its own looping logic (keeps the interface simple): + * + * - <5ms : loops at 1ms intervals. + * - <20ms : loops at 2ms intervals. + * - 20-100ms : loops at 5ms intervals. + * + * @param timeout : timeout measured in ms. + */ + void block(const unsigned long &timeout = 500); + /** + * @brief Switch to unblocked mode for reading. + * + * This causes the serial port to automatically return from a read, even + * if there is no data available. + */ + void unblock(); + + /********************* + ** Reading + **********************/ + /** + * @brief Get the number of bytes remaining in the buffer, but do not read. + * + * Check the serial port's buffer to determine how many bytes are left in the buffer for reading. + * + * @return int : the number of bytes in the buffer + **/ + long remaining(); + /** + * @brief Read a character from the port. + * + * Uses the current device configuration + * for reading. The blocking policy is defined by the current parameters + * of the port. + * + * This function gives a compile time error if the type is not a byte (refer to ecl_mpl's) + * is_byte type traits. + * + * @param byte : character to read into from the serial port's buffer. + * @exception StandardException : throws reading returned an error [debug mode only]. + **/ + template + long read(Byte &byte); + /** + * @brief Read a character string from the port. + * + * Uses the current device configuration + * for reading. The blocking policy is defined by the current parameters + * of the port. + * + * This function gives a compile time error if the type is not a byte (refer to ecl_mpl's) + * is_byte type traits. + * + * @param bytes : character string to read into from the serial port's buffer. + * @param n : the number of bytes to read. + * @exception StandardException : throws reading returned an error [debug mode only]. + **/ + template + long read(Byte *bytes, const unsigned long &n); + + /********************* + ** Serial Specific + **********************/ + /** + * @brief Clear both input and output buffers. + * + * Serial input and output buffers are managed by the system. This clears + * them both. + */ + void clear() + { tcflush(file_descriptor,TCIOFLUSH);} + /** + * @brief Clear the input buffer. + * + * The serial input buffer are managed by the system. This clears it. + */ + void clearInputBuffer() + { tcflush(file_descriptor,TCIFLUSH);} + /** + * @brief Clear the output buffer. + * + * The serial output buffer are managed by the system. This clears it. + */ + void clearOutputBuffer() + { tcflush(file_descriptor,TCOFLUSH);} + + /** + * @brief Return the latest error state for this serial object. + * + * Return the error result from the last used open/read/write + * method in this class. + */ + const Error& error() const + { return error_handler;} + private: + /********************* + ** Constants + **********************/ + enum { + NonBlocking = -1 + }; + /********************* + ** Variables + **********************/ + int file_descriptor; + termios options; + std::string port; + long read_timeout_ms; + ecl::Snooze fake_snooze; + unsigned int fake_loop_count; + bool is_open; + ecl::Error error_handler; + }; + + /***************************************************************************** + ** Template Implementations + *****************************************************************************/ + + template + long Serial::write(const Byte &byte) + { + ecl_compile_time_assert( is_byte::value ); + if ( !is_open ) // internal check only, don't worry about doing the full device filename check here (we need speed) + { + ecl_debug_throw( StandardException(LOC, OpenError, std::string("Port ") + port + std::string(" is not open."))); + error_handler = OpenError; + return -1; + } + ssize_t no_written = ::write(file_descriptor, &byte, 1); + if ( no_written < 0 ) + { + ecl_debug_throw(devices::write_exception(LOC)); + error_handler = devices::write_error(); + return -1; + } + error_handler = NoError; + return no_written; + } + + template + long Serial::write(const Byte *bytes, const unsigned long &n) + { + ecl_compile_time_assert( is_byte::value ); + if ( !is_open ) // internal check only, don't worry about doing the full device filename check here (we need speed) + { + ecl_debug_throw( StandardException(LOC, OpenError, std::string("Port ") + port + std::string(" is not open."))); + error_handler = OpenError; + return -1; + } + ssize_t no_written = ::write(file_descriptor, bytes, n); + if ( no_written < 0 ) + { + ecl_debug_throw(devices::write_exception(LOC)); + error_handler = devices::write_error(); + return -1; + } + error_handler = NoError; + return no_written; + } + + template + long Serial::read(Byte &byte) + { + ecl_compile_time_assert( is_byte::value ); + if ( !is_open ) // internal check only, don't worry about doing the full device filename check here (we need speed) + { + ecl_debug_throw( StandardException(LOC, OpenError, std::string("Port ") + port + std::string(" is not open."))); + error_handler = OpenError; + return -1; + } + ssize_t no_read; + if ( ( read_timeout_ms != NonBlocking ) && ( read_timeout_ms < 100 ) ) + { + fake_snooze.initialise(); + for ( unsigned int i = 0; i < fake_loop_count; ++i ) + { + no_read = ::read(file_descriptor, &byte, 1); + if ( no_read != 0 ) + { + break; + } + fake_snooze(); + } + } + else + { + no_read = ::read(file_descriptor, &byte, 1); + } + if ( no_read < 0 ) + { + ecl_debug_throw(devices::read_exception(LOC)); + error_handler = devices::read_error(); + return -1; + } + error_handler = NoError; + return no_read; + + } + + template + long Serial::read(Byte *bytes, const unsigned long &n) + { + ecl_compile_time_assert( is_byte::value ); + if ( !is_open ) // internal check only, don't worry about doing the full device filename check here (we need speed) + { + ecl_debug_throw( StandardException(LOC, OpenError, std::string("Port ") + port + std::string(" is not open."))); + error_handler = OpenError; + return -1; + } + ssize_t no_read = 0; + if ( ( read_timeout_ms != NonBlocking ) && ( read_timeout_ms < 100 ) ) + { + fake_snooze.initialise(); + for ( unsigned int i = 0; i < fake_loop_count; ++i ) + { + no_read = ::read(file_descriptor, bytes, n); + if ( no_read != 0 ) + { + break; + } + fake_snooze(); + } + } + else + { + no_read = ::read(file_descriptor, bytes, n); + } + if ( no_read < 0 ) + { + ecl_debug_throw(devices::read_exception(LOC)); + error_handler = devices::read_error(); + return -1; + } + error_handler = NoError; + return no_read; + } + + /***************************************************************************** + ** Traits [Serial] + *****************************************************************************/ + /** + * @brief Serial sink (output device) trait. + * + * Specialisation for the serial sink (output device) trait. + */ + template <> + class is_sink : public True + {}; + + /** + * @brief Serial sink (input device) trait. + * + * Specialisation for the serial sink (input device) trait. + */ + template <> + class is_source : public True + {}; + + /** + * @brief Serial sourcesink (input-output device) trait. + * + * Specialisation for the serial sourcesink (input-output device) trait. + */ + template <> + class is_sourcesink : public True + {}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_DEVICES_SERIAL_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_w32.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_w32.hpp new file mode 100644 index 0000000..7cc063a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/serial_w32.hpp @@ -0,0 +1,365 @@ +/** + * @file /ecl_devices/include/ecl/devices/serial_w32.hpp + * + * @brief Win32 interface for serial (RS232) devices. + * + * @date May 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_SERIAL_W32_HPP_ +#define ECL_THREADS_SERIAL_W32_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#ifdef ECL_IS_WIN32 + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "serial_parameters.hpp" +#include "traits.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Serial] +*****************************************************************************/ +/** + * @brief Win32 implementation for a serial (RS232) device. + * + * This device is a c++ wrapper around the win32 api for serial (RS232 devices). It + * configures the serial device as a non-seekable source-sink (read-write), + * device. + * + * Just a quick note about the serial termios functions. They can + * be configured in a variety of ways for a variety of + * situations (modems, terminals, login consoles). Most of these are + * redundant for control, so we just keep it simple here + * and use a simple wrapper around a useful configuration for + * control. This keeps + * options and settings to a minimum and lets us get on with the job + * of control. + * + * Read Modes + * + * In posix, there are several available read modes. As mentioned above, + * some of these are for all intents and purposes, redundant for control. + * One particular example is the message + * buffering configuration that uses both a packet size limit as well + * as an inter-byte timeout when reading. Unfortunately the minimum inter-byte + * timeout is a massive 200ms, which makes it all but useless for + * control. + * + * Subsequently, the default mode of operation is using + * a timeout - as this one will automatically return you whenever any + * new data comes in. Great for control! An alternative non-blocking option is + * also provided. + * + * Usage: + * + * The serial device does both input and output, using the usual read/write + * interface with your preference of RAII/non-RAII style interface. In either + * case, the serial class does the cleanup for you in the destructor. + * + * Protocol configuration is done either in the constructor or the open() + * command by passing a port name and a set of enumerated + * protocol configuration parameters - @ref BaudRate "baud rate", + * @ref DataBits "data bits", @ref StopBits "stop bits", + * and @ref Parity "parity" are defined via enums. + * + * @code + * Serial serial_raii("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // RAII + * Serial serial_nonraii; + * serial_nonraii.open("/dev/ttyS0",BaudRate_115200,DataBits_8,StopBits_1,NoParity); // non-RAII + * @endcode + * + * Reading with various timeouts. + * + * @code + * int n; + * char buffer[256]; + * serial.block(500); // timeout of 500ms + * n = serial.read(buffer,256); + * serial.unblock(); + * n = serial.read(buffer,256); // always returns, even if nothing is there. + * @endcode + * + * Writing: + * + * @code + * serial.write("Dude\n",5); + * @endcode + * + * @todo Another option in future would be to utilise the asynchronous + * configuration mode for serial ports (see + * http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN144). + * This might get around some bottlenecking io performance problems. + */ +class ecl_devices_PUBLIC Serial { +public: + /********************* + ** C&D + **********************/ + /** + * @brief Non-RAII style constructor, doesn't make a connection. + * + * Sometimes its more convenient to open manually rather than inside + * constructors. Use this with the open() command to do so. You can + * check for open status with via the open accessor. + */ + Serial() : is_open(false), is_run(false), file_descriptor(INVALID_HANDLE_VALUE), error_handler(NoError) {}; + /** + * @brief Constructs and opens the connection, RAII style. + * + * Configures and opens the serial device (RAII style) with the specified + * parameters. + * + * By default, the port is configured to read in blocking mode + * (with no timeouts) - use the block(), block(timeout_ms) and unbock() + * methods to alter its behaviour. + * @param port_name : the device name. + * @param baud_rate : baud rate. + * @param data_bits : the number of bits in a single message byte. + * @param stop_bits : the number of bits after the data used for error checking. + * @param parity : the parity used for checksums. + * @exception StandardException : throws if the connection failed to open. + */ + Serial(const std::string& port_name, const BaudRate &baud_rate = BaudRate_115200, const DataBits &data_bits = DataBits_8, + const StopBits &stop_bits = StopBits_1, const Parity &parity = NoParity ); + + /** + * @brief Cleans up the file descriptor. + * + * Cleans up the file descriptor. + */ + virtual ~Serial(); + + /********************* + ** Open/Close + **********************/ + /** + * @brief Opens the connection. + * + * Configures and opens the serial device with the specified + * parameters. You don't need to do this if you constructed this class with the RAII + * style constructor. + * + * If the device is already open, it will first close and then reopen the device. + * + * @param port_name : the device name. + * @param baud_rate : baud rate. + * @param data_bits : the number of bits in a single message byte. + * @param stop_bits : the number of bits after the data used for error checking. + * @param parity : the parity used for checksums. + * @exception StandardException : throws if the connection failed to open. + */ + void open(const std::string& port_name, const BaudRate &baud_rate = BaudRate_115200, const DataBits &data_bits = DataBits_8, + const StopBits &stop_bits = StopBits_1, const Parity &parity = NoParity ); + + /** + * @brief Closes the port connection. + * + * The destructor automatically handles this, so in most cases its redundant. + * However there are times when a serial port must be temporarily closed. + * This enables you to do that. + */ + void close(); + /** + * @brief Status flag indicating if the serial port is open/closed. + * + * True if the serial port is open and connected, false otherwise. + */ + bool open() const { return is_open; } + + /********************* + ** Writing + **********************/ + /** + * @brief Write a character to the serial port. + * + * Write a character to the serial port. + * + * @param c : the character to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char &c); + + /** + * @brief Write a character string to the serial port. + * + * Write a character string to the serial port. + * @param s : points to the beginning of the character string. + * @param n : the number of characters to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char *s, unsigned long n); + + /** + * @brief A dummy flush function, not used, but needed by streams. + * + * This is unused - but is included so as to implement streaming functionality + * on top of this device. + */ + void flush() {} + + /********************* + ** Reading Modes + **********************/ + /** + * @brief Switch to blocking mode with a timeout for reading. + * + * Switched to blocking mode with the specified timeout in milliseconds. + * + * @param timeout : timeout measured in ms. + * + * @exception StandardException : throws if a timeout < 0 is specified [debug mode only]. + */ + void block(const long &timeout = 500); + /** + * @brief Switch to unbocked mode for reading. + * + * This causes the serial port to automatically return from a read, even + * if there is no data available. + */ + void unblock(); + + /********************* + ** Reading + **********************/ + /** + * @brief Get the number of bytes remaining in the buffer, but do not read. + * + * Check the serial port's buffer to determine how many bytes are left in the buffer for reading. + * + * @return int : the number of bytes in the buffer + **/ + long remaining(); + /** + * @brief Read a character from the port. + * + * Uses the current device configuration + * for reading. The blocking policy is defined by the current parameters + * of the port. + * + * @param c : character to read into from the serial port's buffer. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char &c); + /** + * @brief Read a character string from the port. + * + * Uses the current device configuration + * for reading. The blocking policy is defined by the current parameters + * of the port. + * + * @param s : character string to read into from the serial port's buffer. + * @param n : the number of bytes to read. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char *s, const unsigned long &n); + + + /********************* + ** Serial Specific + **********************/ + /** + * @brief Clear both input and output buffers. + * + * Serial input and output buffers are managed by the system. This clears + * them both. + */ + void clear() { + PurgeComm( file_descriptor, PURGE_RXCLEAR ); + PurgeComm( file_descriptor, PURGE_TXCLEAR ); + } + /** + * @brief Clear the input buffer. + * + * The serial input buffer are managed by the system. This clears it. + */ + void clearInputBuffer() { PurgeComm( file_descriptor, PURGE_RXCLEAR ); } + /** + * @brief Clear the output buffer. + * + * The serial output buffer are managed by the system. This clears it. + */ + void clearOutputBuffer() { PurgeComm( file_descriptor, PURGE_TXCLEAR ); } + + /** + * @brief Return the latest error state for this serial object. + * + * Return the error result from the last used open/read/write + * method in this class. + */ + const Error& error() const { return error_handler; } + +private: + /********************* + ** Variables + **********************/ + HANDLE file_descriptor; + OVERLAPPED m_osRead, m_osWrite; // Offsets + std::string port; + bool is_open; + ecl::Error error_handler; + Thread event_receiver; + bool is_run; + +private: + /** + * @brief Threading procedure for serial port. + * + * Receiving event generated by communication port. + */ + friend void event_proc(void* arg); + +}; + +/***************************************************************************** +** Traits [Serial] +*****************************************************************************/ +/** + * @brief Serial sink (output device) trait. + * + * Specialisation for the serial sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +/** + * @brief Serial sink (input device) trait. + * + * Specialisation for the serial sink (input device) trait. + */ +template <> +class is_source : public True {}; + +/** + * @brief Serial sourcesink (input-output device) trait. + * + * Specialisation for the serial sourcesink (input-output device) trait. + */ +template <> +class is_sourcesink : public True {}; + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_THREADS_SERIAL_W32_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/shared_file.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/shared_file.hpp new file mode 100644 index 0000000..179c9a9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/shared_file.hpp @@ -0,0 +1,250 @@ +/** + * @file /include/ecl/devices/shared_file.hpp + * + * @brief Output file specially suited for logging across threads. + * + * Output file specially suited for logging across threads. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SHARED_FILE_HPP_ +#define ECL_DEVICES_SHARED_FILE_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "detail/character_buffer.hpp" +#include "ofile.hpp" +#include "traits.hpp" +#include "modes.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Definition +*****************************************************************************/ + +class SharedFile; + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +namespace devices { + +/***************************************************************************** +** Interface [SharedFileCommon] +*****************************************************************************/ +/** + * @brief Interface distributed to all members of a shared output file. + * + * Contains the objects required to be distributed amongst all members + * of a shared output file. + */ +class SharedFileCommon { +public: + SharedFileCommon() : error_handler(NoError) {}; + /** + * @brief Automatically opens a file and initialises the count. + * + * Automatically opens a file and initialises the count. + * + * @param name : file name. + * @param mode : writing mode (either New or Append). + */ + SharedFileCommon(const std::string &name, ecl::WriteMode mode); + virtual ~SharedFileCommon() {} + + friend class ecl::SharedFile; + friend class SharedFileManager; + +private: + unsigned int count; + ecl::Mutex mutex; + OFile file; + Error error_handler; +}; + +class SharedFileManager { +public: + static SharedFileCommon* RegisterSharedFile(const std::string &name, ecl::WriteMode mode = New); + static bool DeRegisterSharedFile(const std::string &name); +private: + static ecl::Mutex mutex; + static std::map opened_files; +}; + +} // namespace devices + +/***************************************************************************** +** Interface [SharedFile] +*****************************************************************************/ +/** + * @brief Multi-instance (also thread-safe) output file device. + * + * This allows multiple instantiations/connections (uniquely identified by string file name) + * to an OFile device. Each instantiation has its own buffer that protects + * data from multiple sources getting unnecessarily tangled. It is also thread-safe. + * + * Usage: + * + * Usage is exactly the same as that for regular OFile devices except that no new + * files are made if the same file name is used (instead, instantiations share + * this file). Everything else happens under the hood and cleanup occurs in the + * destructors. + * + * @sa OFile. + */ +class ecl_devices_PUBLIC SharedFile { +public: + /********************* + ** C&D + **********************/ + /** + * @brief Non-RAII style constructor, doesn't open a file. + * + * Sometimes its more convenient to open manually rather than inside + * constructors. Use this with the open() command to do so. You can + * check for open status via the open accessor. + */ + SharedFile() {}; + /** + * @brief Either opens a file for writing or a link to an existing shared instance. + * + * If a file by this name is not yet being shared, then it opens it directly. + * Otherwise it opens a link to the shared instance. Note, you may ignore + * the second argument (mode) if you are simply opening a second link to the + * shared instance. + * + * @param name : filename. + * @param mode : mode for writing (New, Append), this must be the same for all instances. + * + * @exception StandardException : throws if the file could not be opened. + */ + SharedFile(const std::string &name, WriteMode mode = New); + /** + * @brief Automatic cleaner for shared files. + * + * Automatically cleans up and closes io handles. + */ + virtual ~SharedFile(); + + /** + * @brief Opens the file for writing. + * + * Configures and opens the file for writing in either New or Append mode. + * Note, that you don't need to do this if you constructed this class with the RAII + * style constructor as it gets automatically called. + * + * Error handling the same for OFile's open() call. + * + * @param name : name of the file to open. + * @param mode : mode of writing, either New or Append. + * @exception StandardException : throws if the connection failed to open. + * @sa OFile + */ + bool open(const std::string &name, WriteMode mode = New); + + /********************* + ** Shared File Methods + **********************/ + /** + * @brief Denotes how many instances are currently sharing this file. + * + * Denotes how many instances are currently sharing this file. + * + * @return unsigned int : the number of shared instances. + */ + unsigned int count() { return shared_instance->count; } + + /********************* + ** OutputDevice Methods + **********************/ + /** + * @brief Status flag indicating if the file is open/closed. + * + * @return bool : true if open, false otherwise. + */ + bool open() { return shared_instance->file.open(); } + /** + * @brief Write a character to the buffer. + * + * Write a character to the buffer. It will automatically flush (write to + * the shared ofile instance) if the buffer exceeds its capacity. + * + * Error handling the same for OFile's write function. + * + * @param c : the character to write. + * @return long : the number of bytes written. + * + * @exception StandardException : throws from the underlying file if writing returned an error [debug mode only]. + * @sa OFile + **/ + long write(const char &c); + /** + * @brief Write a character string to the buffer. + * + * Write a character string to the buffer. It will automatically flush (write to + * the shared ofile instance) if the buffer exceeds its capacity. + * + * Error handling the same for OFile's write function. + * + * @param s : points to the beginning of the character string. + * @param n : the number of characters to write. + * @return long: the number of bytes written. + * + * @exception StandardException : throws from the underlying file if flushing returned an error [debug mode only]. + * @sa OFile + **/ + long write(const char* s, unsigned long n); + /** + * @brief Flush the internal buffer. + * + * This writes to the shared file. Error handling the same for OFile's write function. + * + * @exception StandardException : throws from the underlying file if flushing returned an error [debug mode only]. + * @sa OFile + **/ + bool flush(); + + const Error& error() const { return shared_instance->error_handler; } + +private: + devices::SharedFileCommon* shared_instance; + devices::CharBuffer buffer; +}; + +/***************************************************************************** +** Traits [SharedFile] +*****************************************************************************/ +/** + * @brief File sink (output device) trait. + * + * Specialisation for the file sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +} // namespace ecl + +#endif /* ECL_DEVICES_SHARED_FILE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket.hpp new file mode 100644 index 0000000..ecf962e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket.hpp @@ -0,0 +1,34 @@ +/** + * @file /include/ecl/devices/socket.hpp + * + * @brief Cross platform server tcp/ip socket header. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SOCKET_HPP_ +#define ECL_DEVICES_SOCKET_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "socket_connection_status.hpp" + +#if defined(ECL_IS_POSIX) + #ifndef ECL_IS_APPLE + #include "socket_client_pos.hpp" + #include "socket_server_pos.hpp" + #endif +#endif + +#endif /* ECL_DEVICES_SOCKET_SERVER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_client_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_client_pos.hpp new file mode 100644 index 0000000..6e957c4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_client_pos.hpp @@ -0,0 +1,233 @@ +/** + * @file /include/ecl/devices/socket_client_pos.hpp + * + * @brief Posix interface for a simple tcp/ip client. + * + * Posix interface for a simple tcp/ip client. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SOCKET_CLIENT_POS_HPP_ +#define ECL_DEVICES_SOCKET_CLIENT_POS_HPP_ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // inet_addr() +#include +#include +#include // used in remaining() +#include +#include +#include +#include "socket_connection_status.hpp" +#include "detail/socket_error_handler_pos.hpp" +#include "traits.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [SocketClient] +*****************************************************************************/ +/** + * @brief Simple implementation of an ipv4 socket client. + * + * This is certainly not industrial strength - use a proper library for that. + * Rather, this is designed to merely fill a simple need, such as that of + * building a cross-platform remote debugging program. + * + * Usage is simple, simply specify the server host name and the port number + * when constructing, the + * rest of the configuration happens under the hood. From there, the usual + * read/write pair work, or alternatively a stream can be hooked up to it. + * + * @sa @ref SocketServer "SocketServer". + */ +class SocketClient { +public: + /********************* + ** C&D + **********************/ + SocketClient() : is_open(false), error_handler(NoError) {}; /**< @brief Default constructor, use with open(). **/ + /** + * @brief Automatically configures, opens and begins listening on the specified port. + * + * This is the RAII constructor which does all the configuration and setup for the + * port. Once done, it has already started its job and is listening on the specified + * port number. + * + * @param host_name : name of the server to connect to. + * @param port_number : port on which to listen for connections. + * @exception StandardException : throws if the connection failed to open. + **/ + SocketClient(const std::string &host_name, const unsigned int &port_number = 5555); + virtual ~SocketClient() { close(); } /**< @brief If connected, closes the connection to the server. **/ + + /********************* + ** Configuration + **********************/ + /** + * @brief Opens the connection. + * + * Configures and opens the socket with the specified + * parameters. You don't need to do this if you constructed this + * class with the RAII style constructor. + * + * @param hostname : name of the server to connect to. + * @param port_number : port on which to listen for connections. + * @exception StandardException : throws if the connection failed to open. + **/ + bool open( const std::string &hostname, const unsigned int& port_number ); + void close(); /**< @brief If open, close the link to the server. **/ + + bool open() const { return is_open; } + + /********************* + ** Writing + **********************/ + /** + * @brief Write a character to the serial port. + * + * Write a character to the serial port. + * + * @param c : the character to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char &c); + + /** + * @brief Write a character string to the serial port. + * + * Write a character string to the serial port. + * @param s : points to the beginning of the character string. + * @param n : the number of characters to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char *s, unsigned long n); + + /** + * @brief Maybe all that is needed is a dummy flush (not sure). + * + * How to flush these? Tutorials dont seem to cover it. Maybe fflush? Not + * terribly important. + */ + void flush() {} + + /********************* + ** Reading + **********************/ + /** + * @brief Get the number of bytes remaining in the buffer, but do not read. + * + * Check the serial port's buffer to determine how many bytes are left in the buffer for reading. + * + * @return int : the number of bytes in the buffer + **/ + long remaining(); + /** + * @brief Read a character from the port. + * + * Simply passes along the read work to its big brother. + * + * @param c : character to read into from the buffer. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char &c); + /** + * @brief Read a character string from the port. + * + * Note that by + * default, posix socket connections will wait if there is nothing to read + * and as soon as something arrives, it will return, regardless of whether + * n requested bytes have arrived or not. It is possible to implement non-blocking + * behaviour, but that will use valuable cpu cycles. Better to just let + * posix sleep the system inbetween arrivals and deal with them as they come + * in (possibly implementing your own buffer which is fed from posix calls + * made by this class is a good idea). + * + * This will return @ref ConnectionHungUp "ConnectionHungup" if + * it returns with zero bytes (it's blocked and waiting by default, see above). + * + * @param s : character string to read into from the buffer. + * @param n : the number of bytes to read. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char *s, const unsigned long &n); + /** + * @brief Reads at the incoming socket buffer, but doesn't remove from the buffer. + * + * Reads, but doesn't actually read the contents of the incoming buffer. + * Try to avoid using this for polling - it is an inefficient + * way to retrieve data. + * + * @param s : variable to store the characters in. + * @param n : the desired number of characters to read. + * @return long : number of characters read (-1 implies an error). + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long peek(char*s, const unsigned long &n); + + /** + * @brief Reports on the error state of the last operation. + */ + const Error& error() const { return error_handler; } + +private: + std::string hostname; + int port; + int socket_fd; + bool is_open; + ecl::Error error_handler; +}; + +/***************************************************************************** +** Traits [Serial] +*****************************************************************************/ +/** + * @brief Serial sink (output device) trait. + * + * Specialisation for the serial sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +/** + * @brief Serial sink (input device) trait. + * + * Specialisation for the serial sink (input device) trait. + */ +template <> +class is_source : public True {}; + +/** + * @brief Serial sourcesink (input-output device) trait. + * + * Specialisation for the serial sourcesink (input-output device) trait. + */ +template <> +class is_sourcesink : public True {}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ + +#endif /* ECL_DEVICES_SOCKET_CLIENT_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_connection_status.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_connection_status.hpp new file mode 100644 index 0000000..ecaf67b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_connection_status.hpp @@ -0,0 +1,40 @@ +/** + * @file /include/ecl/devices/socket_connection_status.hpp + * + * @brief Various connection status flags. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_CONNECTION_STATUS_HPP_ +#define ECL_DEVICES_CONNECTION_STATUS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Enums +*****************************************************************************/ + +/** + * @brief Used to denote the status of a connection. + */ +enum ConnectionStatus { + ConnectionProblem = -1, /**< @brief Was some error in the last operation.. **/ + ConnectionDisconnected = -2, /**< @brief Used to state when a server/client detects that there is no other connection at the other end. **/ + ConnectionHungUp = -3 /**< @brief Used to signify when a server/client detects that the other end has 'hung up'. **/ +}; + +} // namespace ecl + +#endif /* ECL_DEVICES_CONNECTION_STATUS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_server_pos.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_server_pos.hpp new file mode 100644 index 0000000..4cddb84 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/socket_server_pos.hpp @@ -0,0 +1,255 @@ +/** + * @file /include/ecl/devices/socket_server_pos.hpp + * + * @brief Posix interface for a simple tcp/ip server. + * + * Posix interface for a simple tcp/ip server. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_SOCKET_SERVER_POS_HPP_ +#define ECL_DEVICES_SOCKET_SERVER_POS_HPP_ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // inet_addr() +#include // used in remaining() +#include +#include + +#include "detail/socket_error_handler_pos.hpp" +#include "detail/socket_exception_handler_pos.hpp" +#include "traits.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [SocketServer] +*****************************************************************************/ +/** + * @brief Simple implementation of an ipv4 socket server. + * + * This is certainly not industrial strength - use a proper library for that. + * Rather, this is designed to merely fill a simple need, such as that of + * building a cross-platform remote debugging program. + * + * Usage is simple, simply specify the port number when constructing, the + * rest of the configuration happens under the hood. From there, the usual + * read/write pair work, or alternatively a stream can be hooked up to it. + * + * @sa @ref SocketClient "SocketClient". + */ +class SocketServer { +public: + /********************* + ** C&D + **********************/ + SocketServer() : is_open(false) {}; /**< @brief Default constructor, use with open(). **/ + /** + * @brief Automatically configures, opens and begins listening on the specified port. + * + * This is the RAII constructor which does all the configuration and setup for the + * port. Once done, it has already started its job and is listening on the specified + * port number. + * + * @param port_number : port on which to listen for connections. + * @exception StandardException : throws if the connection failed to open. + **/ + SocketServer(const unsigned int &port_number); + virtual ~SocketServer() { close(); }; /**< @brief If connected, close down the connection to the client. **/ + + /********************* + ** Configuration + **********************/ + /** + * @brief Opens the connection. + * + * Configures and opens the socket with the specified + * parameters. You don't need to do this if you constructed this + * class with the RAII style constructor. + * + * @param port_number : port on which to listen for connections. + * @exception StandardException : throws if the connection failed to open. + **/ + bool open( const unsigned int& port_number ); + /** + * @brief If connected to a client, terminate the connection. + * + * There's a peculiarity which + * often pops up with these - even after closing, you will still + * get an ECONNREFUSED if your client tries immediately to connect + * again. This is because even though the interface gets closed, it + * may be there are packets out there floating around on the net + * still waiting to be delivered, so the kernel generally + * keeps it alive for a few minutes after you close it. From the + * c++ newsgroups: + * + * It is normal, for example for the socket to go into a TIME_WAIT state, + * on the server side, for a few minutes. People have reported ranges + * from 20 seconds to 4 minutes to me. The official standard says + * that it should be 4 minutes. + */ + void close() { is_open = false; ::close(socket_fd); } + + bool open() const { return is_open; } + + /********************* + ** Writing + **********************/ + /** + * @brief Write a character to the serial port. + * + * Write a character to the serial port. + * + * @param c : the character to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char &c) { return write(&c,1); } + + /** + * @brief Write a character string to the serial port. + * + * Write a character string to the serial port. + * @param s : points to the beginning of the character string. + * @param n : the number of characters to write. + * @exception StandardException : throws if writing returned an error [debug mode only]. + **/ + long write(const char *s, unsigned long n); + + /** + * @brief A dummy flush function, not used, but needed by streams. + * + * This is unused - but is included so as to implement streaming functionality + * on top of this device. + */ + void flush() {} + + /********************* + ** Reading + **********************/ + /** + * @brief Get the number of bytes remaining in the buffer, but do not read. + * + * Check the serial port's buffer to determine how many bytes are left in the buffer for reading. + * + * @return int : the number of bytes in the buffer + **/ + long remaining(); + /** + * @brief Read a character from the port. + * + * Note that by + * default, posix socket connections will wait if there is nothing to read + * and as soon as something arrives, it will return, regardless of whether + * n requested bytes have arrived or not. It is possible to implement non-blocking + * behaviour, but that will use valuable cpu cycles. Better to just let + * posix sleep the system inbetween arrivals and deal with them as they come + * in (possibly implementing your own buffer which is fed from posix calls + * made by this class is a good idea). + * + * This will return @ref ConnectionHungUp "ConnectionHungup" if + * it returns with zero bytes (it's blocked and waiting by default, see above). + * + * @param c : character to read into from the serial port's buffer. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char &c) { return read(&c,1); } + /** + * @brief Read a character string from the port. + * + * Simply passes along the read work to its big brother. + * + * @param s : character string to read into from the serial port's buffer. + * @param n : the number of bytes to read. + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long read(char *s, const unsigned long &n); + /** + * @brief Reads at the incoming socket buffer, but doesn't remove from the buffer. + * + * Reads, but doesn't actually read the contents of the incoming buffer. + * + * @param s : variable to store the characters in. + * @param n : the desired number of characters to read. + * @return long : number of characters read (-1 implies an error). + * @exception StandardException : throws if reading returned an error [debug mode only]. + **/ + long peek(char*s, const unsigned long &n); + + /********************* + ** Socket Specific + **********************/ + /** + * @brief Listens for incoming connections. + * + * Listen for a client connection and return the handle to the file descriptor. + * + * @return int : client socket descriptor. + * @exception StandardException : throws if the server could not begin listening. + **/ + int listen(); + + /** + * @brief Reports on the error state of the last operation. + */ + const Error& error() const { return error_handler; } + +private: + int port; + int socket_fd; + int client_socket_fd; + bool is_open; + Error error_handler; +}; + +/***************************************************************************** +** Traits [Serial] +*****************************************************************************/ +/** + * @brief Serial sink (output device) trait. + * + * Specialisation for the serial sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +/** + * @brief Serial sink (input device) trait. + * + * Specialisation for the serial sink (input device) trait. + */ +template <> +class is_source : public True {}; + +/** + * @brief Serial sourcesink (input-output device) trait. + * + * Specialisation for the serial sourcesink (input-output device) trait. + */ +template <> +class is_sourcesink : public True {}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ + +#endif /* ECL_DEVICES_SOCKET_SERVER_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/string.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/string.hpp new file mode 100644 index 0000000..dcfb2fc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/string.hpp @@ -0,0 +1,245 @@ +/** + * @file /include/ecl/devices/string.hpp + * + * @brief A virtual string device. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_STRING_HPP_ +#define ECL_DEVICES_STRING_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "traits.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [String] +*****************************************************************************/ +/** + * @brief A virtual device for manipulating strings. + * + * Device for streaming to and from a string. Do not use this class directly, + * rather use the string stream class instead. It has flexible memory storage + * and will grow as needed to (similar to the c++ string class) but the + * growing algorithm isn't really intelligent - just jumps in leaps of 256. + * + * Reading and writing are simplified. Two separate pointers are used to + * designate writing and reading locations on the internal buffer. + * + * Reading does not remove or modify the internal + * buffer, it simply shifts the read location pointer along the string. + * + * Writing always appends and reading has nothing to do whatsoever with the + * state of the write pointer. + **/ +class ecl_devices_PUBLIC String { +public: + /** + * @brief Initialises the string device. + * + * Configures the strings buffer with the input character string. + * If unspecified, it leaves the internal buffer empty. + * + * @param str : the input string to store in the buffer. + **/ + explicit String(const char* str = ""); + /** + * @brief Cleans up memory allocations. + * + * Cleans up the memory allocated to the buffer. + */ + virtual ~String(); + + /********************* + ** String Interface + **********************/ + /** + * @brief Character string representation of the device's contents. + * + * This returns a null terminates string representing the contents of the + * device's internal buffer. + * + * @return const char* : pointer to the device's internal buffer. + */ + const char* c_str(); + /** + * @brief String representation of the device's contents. + * + * This generates a c++ style string representing the contents of the + * device's internal buffer. + * + * @return string : string representation of the device's internal buffer. + */ + std::string str(); + /** + * @brief Clears the device's internal buffers. + * + * Clears the internal character buffer and resets read/write location + * pointers. + */ + void clear(); + + /****************************************** + ** Device Source Interface + *******************************************/ + /** + * @brief Read a character from the string device. + * + * Reads a single character from the string device. + * + * @param c : character to read into from the string device. + * @return long : number of bytes written. + **/ + long read(char &c); + /** + * @brief Reads a character string from the string device. + * + * Reads a character string from the string device. + * + * @param s : character string to read into from the string device. + * @param n : the number of bytes to read. + **/ + long read(char* s, unsigned long n); + /** + * @brief Specifies the number of characters remaining to be read.. + * + * Determines the number of unread characters left in the internal + * buffer. + * + * @return unsigned long : number of characters remaining. + */ + unsigned long remaining(); + + /****************************************** + ** Device Sink Interface + *******************************************/ + /** + * @brief Write a character to the buffer. + * + * Write a character to the buffer. It will automatically + * grow the buffer if necessary. + * + * @param c : the character to write. + * @return long : the number of bytes written. + **/ + long write(char c); + /** + * @brief Write a character string to the buffer. + * + * Write a character string to the buffer. It will automatically + * grow the buffer if necessary. + * + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long: the number of bytes written. + * @exception StandardException : throws if flushing returned an error [debug mode only]. + **/ + long write(const char* s, unsigned long n); + + /****************************************** + ** Device Seekable Interface + *******************************************/ + /** + * @brief Number of characters stored in the buffer. + * + * This returns the size of the buffer - note that this is different + * to the number of characters remaining to be read. It is the sum + * of both read and unread parts. + * + * @return unsigned long : number of characters stored in the buffer. + */ + unsigned long size(); + /** + * @brief Unused, but required api for an output device. + * + * This is not used for string devices, but necessary for the + * concept definition of an output device. + */ + void flush() {}; + + /********************* + ** Device Interface + **********************/ + /** + * @brief Unused, but required api for an ecl device. + * + * This is not used for string devices, but necessary for the + * concept definition of an ecl device. + * + * @return bool : always returns true. + */ + bool open() { return true; }; /**< Redundant api for the string device. **/ + /** + * @brief Unused, but required api for an ecl device. + * + * This is not used for string devices, but necessary for the + * concept definition of an ecl device. + * + * @return bool : always returns true. + */ + bool isOpen() { return true; }; /**< Redundant api for the string device. **/ + +private: + unsigned long buffer_length; // Actual reserved memory is this +1 + char *buffer; + char* buffer_cur_write; + char* buffer_cur_read; + /** + * @brief Grow the buffer by the specified amount. + * + * Grows the buffer when necessary. This currently just grows it by 256 + * bytes whenever room runs out (doesn't actually grow, creates a new + * section in memory and copies everything over). + * + * @param no_bytes : the number of bytes to grow by. + */ + void grow(int no_bytes = 256); + +}; + +/***************************************************************************** +** Traits +*****************************************************************************/ + +/** + * @brief String sink (output device) trait. + * + * Specialisation for the serial sink (output device) trait. + */ +template <> +class is_sink : public True {}; + +/** + * @brief String sink (input device) trait. + * + * Specialisation for the serial sink (input device) trait. + */ +template <> +class is_source : public True {}; + +/** + * @brief String sourcesink (input-output device) trait. + * + * Specialisation for the serial sourcesink (input-output device) trait. + */ +template <> +class is_sourcesink : public True {}; + +} // namespace ecl + + +#endif /* ECL_DEVICES_STRING_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/traits.hpp b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/traits.hpp new file mode 100644 index 0000000..5e634e8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/include/ecl/devices/traits.hpp @@ -0,0 +1,76 @@ +/** + * @file /include/ecl/devices/traits.hpp + * + * @brief Traits for devices. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_DEVICES_TRAITS_HPP_ +#define ECL_DEVICES_TRAITS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ +/** + * @brief Default action for detection of source devices (input) (false). + * + * Sets the default value (false) for detection of the source device (input) + * trait. Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_source : public False {}; + +/** + * @brief Default action for detection of sink devices (output) (false). + * + * Sets the default value (false) for detection of the sink device (output) + * trait. Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_sink : public False {}; + +/** + * @brief Default action for detection of source-sink devices (input-output) (false). + * + * Sets the default value (false) for detection of the source-sink device + * (input-output) trait. Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_sourcesink : public False {}; + +/** + * @brief Default action for detection of seekable devices (false). + * + * Sets the default value (false) for detection of the seekable device + * trait. Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_seekable : public False {}; + +} // namespace ecl + +#endif /* ECL_DEVICES_TRAITS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/package.xml b/ros2_ws/src/ecl_core/ecl_devices/package.xml new file mode 100644 index 0000000..308646f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/package.xml @@ -0,0 +1,45 @@ + + + ecl_devices + 1.2.1 + + Provides an extensible and standardised framework for input-output devices. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_devices + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_containers + ecl_errors + ecl_mpl + ecl_threads + ecl_type_traits + ecl_utilities + + ecl_license + ecl_config + ecl_containers + ecl_errors + ecl_mpl + ecl_threads + ecl_type_traits + ecl_utilities + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/src/CMakeLists.txt new file mode 100644 index 0000000..643f4ab --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + +add_subdirectory(examples) \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/src/examples/CMakeLists.txt new file mode 100644 index 0000000..89da14a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/examples/CMakeLists.txt @@ -0,0 +1,22 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_devices_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries( + ecl_demo_${name} + PUBLIC + ${PROJECT_NAME} + ecl_time::ecl_time + ) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_devices_add_demo(serial_timeouts) + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/examples/serial_timeouts.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/examples/serial_timeouts.cpp new file mode 100644 index 0000000..c4a3e06 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/examples/serial_timeouts.cpp @@ -0,0 +1,170 @@ +/** + * @file /ecl_devices/src/examples/serial_timeouts.cpp + * + * @brief File comment + * + * File comment + * + * @date 03/09/2011 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/devices/serial.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +using namespace ecl; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +void print_usage() { + std::cout << "Usage: demo_serial_timeouts [port]" << std::endl; + std::cout << std::endl; + std::cout << " default value for port is /dev/ttyUSB0" << std::endl; +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::string port("/dev/ttyUSB0"); + if ( argc > 1 ) { + std::string arg(argv[1]); + if ( arg == "--help" ) { + print_usage(); + return 0; + } else { + port = argv[1]; + } + } + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Serial Timeouts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* For demo'ing low latency read timeouts on posix systems." << std::endl; + std::cout << "* Timeouts < 100ms use a custom loop, > 100ms use termios." << std::endl; + std::cout << "* Hook this up to a serial cable to test (actual" << std::endl; + std::cout << "* connection not important)." << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Serial serial; + try { + serial.open(port,BaudRate_115200,DataBits_8,StopBits_1,NoParity); + } catch (StandardException &e ) { + std::cout << "[ERROR] : error opening " << port << std::endl; + std::cout << std::endl; + print_usage(); + return 0; + } + TimeStamp time, pre_read_time; + char buffer[256]; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " 100 ms timeouts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* This will use termios to scan." << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + serial.block(100); + for ( unsigned int i = 0; i < 10; ++i ) { + pre_read_time.stamp(); + long result = serial.read(buffer,256); + time.stamp(); + if ( result > 0 ) { + std::cout << "[INFO] : read " << result << " bytes." << std::endl; + } else if ( result == 0 ) { + std::cout << "[INFO] : timed out [" << (time - pre_read_time) << "]." << std::endl; + } else { + std::cout << "[INFO] : error " << result << "." << std::endl; + } + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " 50 ms timeouts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* This will internally scan with 5ms loops." << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + serial.block(50); + // uncomment this to test reading without a timeout on a loopback connection. + // buffer[0] = 'a'; + // buffer[1] = 'b'; + // serial.write(buffer,2); + for ( unsigned int i = 0; i < 10; ++i ) { + pre_read_time.stamp(); + long result = serial.read(buffer,256); + time.stamp(); + if ( result > 0 ) { + std::cout << "[INFO] : read " << result << " bytes." << std::endl; + } else if ( result == 0 ) { + std::cout << "[INFO] : timed out [" << (time - pre_read_time) << "]." << std::endl; + } else { + std::cout << "[INFO] : error " << result << "." << std::endl; + } + } + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " 20 ms timeouts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* This will internally scan with 2ms loops." << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + serial.block(20); + for ( unsigned int i = 0; i < 10; ++i ) { + pre_read_time.stamp(); + long result = serial.read(buffer,256); + time.stamp(); + if ( result > 0 ) { + std::cout << "[INFO] : read " << result << " bytes." << std::endl; + } else if ( result == 0 ) { + std::cout << "[INFO] : timed out [" << (time - pre_read_time) << "]." << std::endl; + } else { + std::cout << "[INFO] : error " << result << "." << std::endl; + } + } + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " 5 ms timeouts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << "* This will internally scan with 1ms loops." << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + serial.block(5); + for ( unsigned int i = 0; i < 10; ++i ) { + pre_read_time.stamp(); + long result = serial.read(buffer,256); + time.stamp(); + if ( result > 0 ) { + std::cout << "[INFO] : read " << result << " bytes." << std::endl; + } else if ( result == 0 ) { + std::cout << "[INFO] : timed out [" << (time - pre_read_time) << "]." << std::endl; + } else { + std::cout << "[INFO] : error " << result << "." << std::endl; + } + } + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/src/lib/CMakeLists.txt new file mode 100644 index 0000000..7973c28 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/CMakeLists.txt @@ -0,0 +1,58 @@ +############################################################################### +# Sources +############################################################################### + +#file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +set(SOURCES + detail/character_buffer.cpp + detail/error_handler.cpp + detail/exception_handler_pos.cpp + #detail/socket_error_handler_pos.cpp + detail/socket_exception_handler_pos.cpp + console.cpp + ofile_pos.cpp + ofile_w32.cpp + serial_pos.cpp # Don't need to split now as I put ifdef guards around the cpp's. Do to the others too! + serial_w32.cpp + shared_file.cpp + socket_client_pos.cpp + socket_server_pos.cpp + string.cpp + ) + +############################################################################### +# Install +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries(${PROJECT_NAME} + ecl_config::ecl_config + ecl_containers::ecl_containers + ecl_errors::ecl_errors + ecl_mpl::ecl_mpl + ecl_threads::ecl_threads + ecl_type_traits::ecl_type_traits + ecl_utilities::ecl_utilities +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/console.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/console.cpp new file mode 100644 index 0000000..b3e1ad6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/console.cpp @@ -0,0 +1,123 @@ +/** + * @file /src/lib/console.cpp + * + * @brief Standard input-output device implementation. + * + * @date October 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/devices/console.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [OConsole] +*****************************************************************************/ + +long OConsole::write(const char &c) +{ + long n = buffer.append(c); + if ( buffer.full() ) { + flush(); + } + return n; +} + +long OConsole::write(const char* s, unsigned long n) +{ + unsigned int no_written = 0; + while ( no_written < n ) { + no_written += buffer.append(s+no_written,n-no_written); + if ( buffer.full() ) { + flush(); + } + } + return n; +} + +void OConsole::flush() { + fputs(buffer.c_str(),stdout); + buffer.clear(); + int result = fflush(stdout); + ecl_assert_throw ( result == 0, StandardException(LOC, WriteError, std::string("Could not flush to the standard output device."))); +} + +/***************************************************************************** +** Implementation [EConsole] +*****************************************************************************/ + +long EConsole::write(const char &c) +{ + long n = buffer.append(c); + if ( buffer.full() ) { + flush(); + } + return n; +} + +long EConsole::write(const char* s, unsigned long n) +{ + unsigned int no_written = 0; + while ( no_written < n ) { + no_written += buffer.append(s+no_written,n-no_written); + if ( buffer.full() ) { + flush(); + } + } + return n; +} + +void EConsole::flush() { + fputs(buffer.c_str(),stderr); + buffer.clear(); + int result = fflush(stderr); + ecl_assert_throw ( result == 0, StandardException(LOC, WriteError, std::string("Could not flush to the standard output device."))); +} + +/***************************************************************************** +** Implementation [IConsole] +*****************************************************************************/ + +long IConsole::read(char &c) +{ + // fgets is a problem, it doesn't read the newline with the character, + // which means the next read from stdin will catch that newline first. + c = static_cast(fgetc(stdin)); + if ( c == EOF ) { + ecl_assert_throw( c != EOF, StandardException(LOC, ReadError, "Failed to read from standard input.")); + return 0; // fallover if not in debug mode. + } else { +// while ( fgetc(stdin) != '\n' ) {} + return 1; + } +} + +long IConsole::read(char* s, const unsigned long &n) +{ + char *result = fgets(s,n,stdin); + if ( result == NULL ) { + ecl_debug_throw( StandardException(LOC, ReadError, "Failed to read from standard input.")); + return 0; // Fallover if not in debug mode. + } else { + // fgets always terminates with a null character, even if it manages + // to read n-1 chars. We also need to make sure we drop the newline + // character that was returned to trigger the input. + size_t length = strlen(s); // This doesn't count the \0 character. +// *(s+length-1) = '\0'; // drop the newline +// return length-1; + return length; + } +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/character_buffer.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/character_buffer.cpp new file mode 100644 index 0000000..1b83d4f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/character_buffer.cpp @@ -0,0 +1,113 @@ +/** + * @file /src/lib/detail/character_buffer.cpp + * + * @brief Implementation for device buffers. + * + * @date November 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../../include/ecl/devices/detail/character_buffer.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Implementation [CharBuffer] +*****************************************************************************/ + + +bool CharBuffer::full() const { + if ( fill_point_marker == buffer_size ) { + return true; + } else { + return false; + } +} + +long CharBuffer::append(const char& c) { + + if ( full() ) { + return 0; + } else { + contents[fill_point_marker] = c; + fill_point_marker++; + return 1; + } +} + +long CharBuffer::append(const char* s, unsigned long n) { + + if ( n <= remaining() ) { + memcpy(&contents[fill_point_marker], s, n); + fill_point_marker += n; + return n; + } else { + unsigned int num_to_copy = remaining(); + memcpy(&contents[fill_point_marker], s, num_to_copy); + fill_point_marker += num_to_copy; + return num_to_copy; + } +} + +void CharBuffer::clear() { + fill_point_marker = 0; +} + + +/***************************************************************************** +** Implementation [CharStringBuffer] +*****************************************************************************/ + +bool CharStringBuffer::full() const { + if ( fill_point_marker == buffer_size ) { + return true; + } else { + return false; + } +} + +long CharStringBuffer::append(const char& c) { + + if ( full() ) { + return 0; + } else { + contents[fill_point_marker] = c; + fill_point_marker++; + return 1; + } +} + +long CharStringBuffer::append(const char* s, unsigned long n) { + + if ( n <= remaining() ) { + memcpy(&contents[fill_point_marker], s, n); + fill_point_marker += n; + return n; + } else { + unsigned int num_to_copy = remaining(); + memcpy(&contents[fill_point_marker], s, num_to_copy); + fill_point_marker += num_to_copy; + return num_to_copy; + } +} + +void CharStringBuffer::clear() { + fill_point_marker = 0; +} + +const char* CharStringBuffer::c_str() { + contents[fill_point_marker] = '\0'; + return &contents[0]; +} + + +} // namespace devices +} // namespace ecl + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/error_handler.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/error_handler.cpp new file mode 100644 index 0000000..8d0dd3a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/error_handler.cpp @@ -0,0 +1,108 @@ +/** + * @file /src/lib/detail/error_handler_pos.cpp + * + * @brief Implements simple error handling for posix devices. + * + * @date April 2009 + **/ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../../include/ecl/devices/detail/error_handler.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Implementation [Exception Handlers] +*****************************************************************************/ + +ecl::Error open_error() { + int error_result = errno; + switch (error_result) { + case ( EINVAL ) : return ecl::Error(ecl::InvalidArgError); + case ( EACCES ) : return ecl::Error(ecl::PermissionsError); + case ( EFBIG ) : case (EOVERFLOW) : + return ecl::Error(ecl::OutOfResourcesError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EISDIR ) : return ecl::Error(ecl::InvalidObjectError); + case ( ELOOP ) : return ecl::Error(ecl::SystemFailureError); + case ( EMFILE ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENFILE ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENAMETOOLONG ) : return ecl::Error(ecl::InvalidArgError); + case ( ENOMEM ) : return ecl::Error(ecl::MemoryError); + case ( ENOSPC ) : return ecl::Error(ecl::OutOfResourcesError); + case ( ENOTDIR ): return ecl::Error(ecl::InvalidObjectError); + case ( EROFS ) : return ecl::Error(ecl::PermissionsError); + case ( ETXTBSY ): return ecl::Error(ecl::UsageError); + default : return ecl::Error(ecl::UnknownError); + } +} + + +ecl::Error write_error() { + int error_result = errno; + switch (error_result) { + case ( EAGAIN ) : return ecl::Error(ecl::BlockingError); + case ( EBADF ) : case (EINVAL) + : return ecl::Error(ecl::InvalidObjectError); + case ( EFAULT ) : return ecl::Error(ecl::OutOfRangeError); + case ( EFBIG ) : return ecl::Error(ecl::MemoryError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EIO ) : return ecl::Error(ecl::SystemFailureError); + case ( ENOSPC ) : return ecl::Error(ecl::OutOfResourcesError); + case ( EPIPE ) : return ecl::Error(ecl::PermissionsError); + default : return ecl::Error(ecl::UnknownError); + } +} + + +ecl::Error read_error() { + int error_result = errno; + switch (error_result) { + case ( EAGAIN ) : return ecl::Error(ecl::BlockingError); + case ( EBADF ) : case (EINVAL) + : return ecl::Error(ecl::PermissionsError); + case ( EFAULT ) : return ecl::Error(ecl::OutOfRangeError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + case ( EIO ) : return ecl::Error(ecl::SystemFailureError); + case ( EISDIR ) : return ecl::Error(ecl::InvalidObjectError); + default : return ecl::Error(ecl::UnknownError); + } +} +ecl::Error sync_error() { + int error_result = errno; + switch (error_result) { + case ( EBADF ) : return ecl::Error(ecl::InvalidArgError); + case ( EIO ) : return ecl::Error(ecl::CloseError); + case ( EROFS ) : case ( EINVAL ) + : return ecl::Error(ecl::NotSupportedError); + default : return ecl::Error(ecl::UnknownError); + } +} +ecl::Error close_error() { + int error_result = errno; + switch (error_result) { + case ( EBADF ) : return ecl::Error(ecl::InvalidArgError); + case ( EIO ) : return ecl::Error(ecl::SystemFailureError); + case ( EINTR ) : return ecl::Error(ecl::InterruptedError); + default : return ecl::Error(ecl::UnknownError); + } +} + +} // namespace devices +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/exception_handler_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/exception_handler_pos.cpp new file mode 100644 index 0000000..bff008f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/exception_handler_pos.cpp @@ -0,0 +1,146 @@ +/** + * @file /src/lib/detail/exception_handler_pos.cpp + * + * @brief Implements exception handling for posix devices. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../../include/ecl/devices/detail/exception_handler_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::ostringstream; +using std::string; +using ecl::StandardException; + + +/***************************************************************************** +** Implementation [Exception Handlers] +*****************************************************************************/ + +StandardException open_exception(const char* loc, const std::string& file_name) { + int error_result = errno; + switch (error_result) { + case ( ENOENT ) : return StandardException(loc, ecl::NotFoundError, file_name + std::string(" could not be found.")); + case ( EINVAL ) : return StandardException(loc, ecl::InvalidArgError, "File mode setting (read/write/append) was incorrectly specified."); + case ( EACCES ) : return StandardException(loc, ecl::PermissionsError, string("Could not open ")+file_name+string(". Access permission was denied.")); + case ( EFBIG ) : case (EOVERFLOW) : + return StandardException(loc, ecl::OutOfResourcesError, string("Could not open ")+file_name+string(". File was too large (you need to use alternative api/configuration).")); + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, string("Could not open ")+file_name+string(". Interrupted by a signal while opening.")); + case ( EISDIR ) : return StandardException(loc, ecl::InvalidObjectError, string("Could not open ")+file_name+string(". This is a directory and not a file.")); + case ( ELOOP ) : return StandardException(loc, ecl::SystemFailureError, string("Could not open ")+file_name+string(". Very nested symbolic link hell.")); + case ( EMFILE ) : return StandardException(loc, ecl::OutOfResourcesError, string("Could not open ")+file_name+string(". This process has already maxxed out its permitted number of open files.")); + case ( ENFILE ) : return StandardException(loc, ecl::OutOfResourcesError, string("Could not open ")+file_name+string(". This system has already maxxed out its permitted number of open files.")); + case ( ENAMETOOLONG ) : return StandardException(loc, ecl::InvalidArgError, string("Could not open ")+file_name+string(". The file name is too long.")); + case ( ENOMEM ) : return StandardException(loc, ecl::MemoryError, string("Could not open ")+file_name+string(". Insufficient memory.")); + case ( ENOSPC ) : return StandardException(loc, ecl::OutOfResourcesError, string("Could not open ")+file_name+string(". The container device (usually hard disk) has insufficient space to create the file.")); + case ( ENOTDIR ): return StandardException(loc, ecl::InvalidObjectError, string("Could not open ")+file_name+string(". Pathname invalid (a directory was not a directory).")); + case ( EROFS ) : return StandardException(loc, ecl::PermissionsError, string("Could not open ")+file_name+string(". Trying to write to a readonly file system.")); + case ( ETXTBSY ): return StandardException(loc, ecl::UsageError, string("Could not open ")+file_name+string(". Trying to write to a currently executing file.")); + default : + { + ostringstream ostream; + ostream << "Unknown errno " << error_result << " [" << strerror(error_result) << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + + +StandardException write_exception(const char* loc) { + int error_result = errno; + switch (error_result) { + case ( EAGAIN ) : return StandardException(loc, ecl::BlockingError, "The device has been marked non blocking and the write would block."); + case ( EBADF ) : case (EINVAL) + : return StandardException(loc, ecl::InvalidObjectError, "The device is not a valid device for writing."); + case ( EFAULT ) : return StandardException(loc, ecl::OutOfRangeError, "The device's write buffer is outside your accessible address space."); + case ( EFBIG ) : return StandardException(loc, ecl::MemoryError, "Tried to write beyond the device's (or process's) size limit."); + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, "A signal interrupted the write."); + case ( EIO ) : return StandardException(loc, ecl::SystemFailureError, "A low level input-output error occured (possibly beyond your control)."); + case ( ENOSPC ) : return StandardException(loc, ecl::OutOfResourcesError, "The device has no room left for the data you are trying to write."); + case ( EPIPE ) : return StandardException(loc, ecl::PermissionsError, "You tried to write to a pipe whose reading end is closed."); + default : + { + ostringstream ostream; + ostream << "Unknown error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + + +StandardException read_exception(const char* loc) { + int error_result = errno; + switch (error_result) { + case ( EAGAIN ) : return StandardException(loc, ecl::BlockingError, "The device has been marked non blocking and the read would block."); + case ( EBADF ) : case (EINVAL) + : return StandardException(loc, ecl::PermissionsError, "The device is not a valid device for reading."); + case ( EFAULT ) : return StandardException(loc, ecl::OutOfRangeError, "The device's read buffer is outside your accessible address space."); + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, "A signal interrupted the read."); + case ( EIO ) : return StandardException(loc, ecl::SystemFailureError, "A low level input-output error occured (possibly beyond your control)."); + case ( EISDIR ) : return StandardException(loc, ecl::InvalidObjectError, "The file descriptor refers to a directory (not readable)."); + default : + { + ostringstream ostream; + ostream << "Unknown error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} +StandardException sync_exception(const char* loc, const std::string &file_name) { + int error_result = errno; + switch (error_result) { + case ( EBADF ) : return StandardException(loc, ecl::InvalidArgError, string("Could not sync ") + file_name + string(", the file descriptor was not valid for writing.")); + case ( EIO ) : return StandardException(loc, ecl::CloseError, string("Could not sync ") + file_name + string(", could not synchronize while closing.")); + case ( EROFS ) : case ( EINVAL ) + : return StandardException(loc, ecl::NotSupportedError, string("Could not sync ") + file_name + string(", file descriptor does not support synchronization.")); + default : + { + ostringstream ostream; + ostream << "Unknown error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} +StandardException close_exception(const char* loc, const std::string &file_name) { + int error_result = errno; + switch (error_result) { + case ( EBADF ) : return StandardException(loc, ecl::InvalidArgError, string("Could not close ") + file_name + string(". The associated file descriptor was not valid.")); + case ( EIO ) : return StandardException(loc, ecl::SystemFailureError, string("Could not close ") + file_name + string(". Closing io problem.")); + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, string("Could not close ") + file_name + string(". Interrupted by a signal.")); + default : + { + ostringstream ostream; + ostream << "Unknown error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +} // namespace devices +} // namespace ecl + + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/socket_exception_handler_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/socket_exception_handler_pos.cpp new file mode 100644 index 0000000..283291a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/detail/socket_exception_handler_pos.cpp @@ -0,0 +1,212 @@ +/** + * @file /src/lib/detail/socket_exception_handler_pos.cpp + * + * @brief Implements exception handling for posix sockets. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include // gethostbyname +#include +#include "../../../include/ecl/devices/detail/socket_exception_handler_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +StandardException socket_exception(const char* loc) { + switch( errno ) { + case ( EACCES ) : return StandardException(LOC,OpenError,"Unable to open socket. Permission to create is denied."); + case ( EAFNOSUPPORT): return StandardException(LOC,NotSupportedError,"Unable to open socket. Your implementation does not support the specified address family (in this case AF_INET or otherwise known as ipv4)."); + case ( EINVAL ) : return StandardException(LOC,InvalidArgError,"Unable to open socket. Unknown or invalid protocol, family."); + case ( EMFILE ) : return StandardException(LOC,OutOfRangeError,"Unable to open socket. Process file table overflow."); + case ( ENFILE ) : return StandardException(LOC,OutOfResourcesError,"Unable to open socket. The system limit on the number of open files has been reached."); + case ( ENOBUFS ) : return StandardException(LOC,MemoryError,"Unable to open socket. Insufficient memory available."); + case ( ENOMEM ) : return StandardException(LOC,MemoryError,"Unable to open socket. Insufficient memory available."); + case ( EPROTONOSUPPORT ) : return StandardException(LOC,NotSupportedError,"Unable to open socket. The protocol type (socket streams) is not supported within this address family (ipv4)."); + default : { + std::ostringstream ostream; + ostream << "Unknown errno [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException bind_exception(const char* loc) { + switch( errno ) { + case ( EACCES ) : return StandardException(LOC,PermissionsError,"Unable to bind the socket. The address is protected (maybe need to be superuser?)."); + case ( EADDRINUSE ) : return StandardException(LOC,BusyError,"Unable to bind the socket. Address already in use (might be timing out, try again in a moment)."); + case ( EBADF ) : return StandardException(LOC,InvalidObjectError,"Unable to bind the socket. Not a valid socket descriptor."); + case ( EINVAL ) : return StandardException(LOC,BusyError,"Unable to bind the socket. The socket is already bound to an address."); + case ( ENOTSOCK ) : return StandardException(LOC,InvalidObjectError,"Unable to bind the socket. The descriptor is a file descriptor, not a socket descriptor."); + case ( EADDRNOTAVAIL ) : return StandardException(LOC,InvalidObjectError,"Unable to bind the socket. Interface does not exist or is not local."); + case ( EFAULT ) : return StandardException(LOC,OutOfRangeError,"Unable to bind the socket. Socket specification is outside the user address space."); + case ( ELOOP ) : return StandardException(LOC,SystemFailureError,"Unable to bind the socket. Too many symbolic links involved."); + case ( ENAMETOOLONG ) : return StandardException(LOC,InvalidArgError,"Unable to bind the socket. Address is too long."); + case ( ENOENT ) : return StandardException(LOC,InvalidObjectError,"Unable to bind the socket. The file does not exist."); + case ( ENOMEM ) : return StandardException(LOC,MemoryError,"Unable to bind the socket. Insufficient kernel memory."); + case ( ENOTDIR ) : return StandardException(LOC,InvalidArgError,"Unable to bind the socket. A component of the path prefix is not a directory."); + case ( EROFS ) : return StandardException(LOC,PermissionsError,"Unable to bind the socket. Socket inode resides on a read only file system."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException accept_exception(const char* loc) { + switch( errno ) { + case ( EWOULDBLOCK ) : return StandardException(LOC,BlockingError,"Unable to accept client connection. The socket is non-blocking and no connections are available."); + case ( EBADF ) : return StandardException(LOC,InvalidObjectError,"Unable to accept client connection. Not a valid socket descriptor."); + case ( ECONNABORTED ): return StandardException(LOC,InterruptedError,"Unable to accept client connection. A connection has been aborted."); + case ( EINTR ) : return StandardException(LOC,InterruptedError,"Unable to accept client connection. A system signal has interrupted."); + case ( EINVAL ) : return StandardException(LOC,UsageError,"Unable to accept client connection. Socket is not listening for connections or address length is invalid."); + case ( EMFILE ) : return StandardException(LOC,OutOfResourcesError,"Unable to accept client connection. The system or per-process limit on files has been reached."); + case ( ENFILE ) : return StandardException(LOC,OutOfResourcesError,"Unable to accept client connection. The system or per-process limit on files has been reached."); + case ( ENOTSOCK ) : return StandardException(LOC,InvalidObjectError,"Unable to accept client connection. The descriptor is a file descriptor, not a socket descriptor.."); + case ( EOPNOTSUPP ) : return StandardException(LOC,InvalidObjectError,"Unable to accept client connection. The client socket is not of type SOCK_STREAM."); + case ( EFAULT ) : return StandardException(LOC,PermissionsError,"Unable to accept client connection. The address argument is not writable by the user."); + case ( ENOBUFS ) : return StandardException(LOC,MemoryError,"Unable to accept client connection. Not enough free memory (buffer or system)."); + case ( ENOMEM ) : return StandardException(LOC,MemoryError,"Unable to accept client connection. Not enough free memory (buffer or system)."); + case ( EPROTO ) : return StandardException(LOC,InvalidArgError,"Unable to accept client connection. Protocol error."); + case ( EPERM ) : return StandardException(LOC,PermissionsError,"Unable to accept client connection. Permissions do not allow this connection."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException receive_exception(const char* loc) { + + switch( errno ) { + case ( EAGAIN || EWOULDBLOCK ) : return StandardException(LOC,InterruptedError,"Unable to read the socket. Probably a timeout occured."); + case ( EBADF ) : return StandardException(LOC,InvalidObjectError,"Unable to read the socket. Bad file descriptor."); + case ( ECONNREFUSED) : return StandardException(LOC,ConnectionError,"Unable to read the socket. Remote host refused the connection (probably not running)."); + case ( EFAULT ) : return StandardException(LOC,SystemFailureError,"Unable to read the socket. Receive buffer has an address problem."); + case ( EINTR ) : return StandardException(LOC,InterruptedError,"Unable to read the socket. Signal interruption."); + case ( EINVAL ) : return StandardException(LOC,InvalidArgError,"Unable to read the socket. Invalid argument was used."); + case ( ENOMEM ) : return StandardException(LOC,MemoryError,"Unable to read the socket. Could not allocate memory for the operation."); + case ( ENOTCONN ) : return StandardException(LOC,ConnectionError,"Unable to read the socket. Has not been connected."); + case ( ENOTSOCK ) : return StandardException(LOC,InvalidObjectError,"Unable to read the socket. The file descriptor does not refer to a socket."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException send_exception(const char* loc) { + + switch( errno ) { + case ( EAGAIN || EWOULDBLOCK ) : return StandardException(LOC,BlockingError,"Unable to write to the socket. Socket is configured as non-blocking and this would block."); + case ( EWOULDBLOCK ) : return StandardException(LOC,BlockingError,"Unable to write to the socket. Socket is configured as non-blocking and this would block."); + case ( EACCES ) : return StandardException(LOC,PermissionsError,"Unable to write to the socket. Permission to write is denied."); + case ( EBADF ) : return StandardException(LOC,InvalidObjectError,"Unable to write to the socket. Bad file descriptor."); + case ( ECONNRESET ) : return StandardException(LOC,InterruptedError,"Unable to write to the socket. Connection reset by peer."); + case ( EFAULT ) : return StandardException(LOC,SystemFailureError,"Unable to write to the socket. Buffer has an address problem."); + case ( EINTR ) : return StandardException(LOC,InterruptedError,"Unable to write to the socket. Signal interruption."); + case ( EINVAL ) : return StandardException(LOC,InvalidArgError,"Unable to write to the socket. Invalid argument was used."); + case ( EISCONN ) : return StandardException(LOC,ConnectionError,"Unable to write to the socket. Connection mismatch???"); + case ( EMSGSIZE ) : return StandardException(LOC,WriteError,"Unable to write to the socket. Socket type required to send atomically, but the size of this message is too large to handle in this way."); + case ( ENOBUFS ) : return StandardException(LOC,OutOfResourcesError,"Unable to write to the socket. Output queue is full (could be caused by transient congestion, but this doesn't usually happen in linux which typically just drops packets)."); + case ( ENOMEM ) : return StandardException(LOC,MemoryError,"Unable to write to the socket. Could not allocate memory for the operation."); + case ( ENOTCONN ) : return StandardException(LOC,ConnectionError,"Unable to write to the socket. Has not been connected."); + case ( ENOTSOCK ) : return StandardException(LOC,InvalidObjectError,"Unable to write to the socket. The file descriptor does not refer to a socket."); + case ( EOPNOTSUPP ) : return StandardException(LOC,NotSupportedError,"Unable to write to the socket. Some api here not supported."); + case ( EPIPE ) : return StandardException(LOC,InterruptedError,"Unable to write to the socket. Local end has been shutdown. Probably bad and will receive a SIGPIPE signal too."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException ioctl_exception(const char* loc) { + + switch( errno ) { + case ( EBADF ) : return StandardException(LOC,InvalidObjectError, "Socket control error. The file descriptor was not valid."); + case ( EFAULT ) : return StandardException(LOC,OutOfRangeError, "Socket control error. Tried to reference inaccessible memory."); + case ( EINVAL ) : return StandardException(LOC,InvalidArgError, "Socket control error. Ioctl input arguments were not valid."); + case ( ENOTTY ) : return StandardException(LOC,InvalidObjectError, "Socket control error. The file descriptor is not valid or this operation may not be performed on it."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException gethostbyname_exception(const char* loc, const std::string& hostname) { + switch( h_errno ) { + case ( HOST_NOT_FOUND ) : { + std::string header; + header += "Unable to correctly determine the server hostname: "; + header += hostname; + return StandardException(LOC,OpenError,header); + } + case ( TRY_AGAIN ) : return StandardException(LOC, OpenError,"A temporary error occurred on an authoritative name server. Try again later."); + case ( NO_ADDRESS ) : return StandardException(LOC,InvalidArgError,"Requested server hostname is valid, but does not have an IP address."); + case ( NO_RECOVERY ) : return StandardException(LOC,UnknownError); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << h_errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +StandardException connection_exception(const char* loc) { + switch( errno ) { + case ( ( EACCES ) || ( EPERM ) ): return StandardException(LOC,PermissionsError,"Write permission on the socket denied or firewalled."); + case ( EADDRINUSE ) : return StandardException(LOC,BusyError,"Address already in use."); + case ( EAFNOSUPPORT ): return StandardException(LOC,NotSupportedError,"Incorrect address family used (no support for AF maybe?"); + case ( EAGAIN ) : return StandardException(LOC,OutOfResourcesError,"No free local ports remaining."); + case ( EALREADY ) : return StandardException(LOC,BlockingError,"Socket is non-blocking and a previous connection attempt has not yet completed (wtf?)."); + case ( EBADF ) : return StandardException(LOC,InvalidObjectError,"Not a valid socket descriptor."); + case ( ECONNREFUSED ): return StandardException(LOC,ConnectionRefusedError,"Connection refused (no-one listening)."); + case ( EFAULT ) : return StandardException(LOC,OutOfRangeError,"Socket specification is outside the user address space."); + case ( EINPROGRESS ) : return StandardException(LOC,BlockingError,"Socket is non-blocking and the connection cannot be completed immediately (try select or poll for writing)."); + case ( EINTR ) : return StandardException(LOC,InterruptedError,"Connection interrupted by a system signal."); + case ( EISCONN ) : return StandardException(LOC,ConnectionError,"This socket is already connected."); + case ( ENETUNREACH ) : + case ( EHOSTUNREACH ): return StandardException(LOC,NotFoundError,"The host is unreachable."); + case ( ENOTSOCK ) : return StandardException(LOC,InvalidObjectError,"This is not a socket file descriptor."); + case ( ETIMEDOUT ) : return StandardException(LOC,TimeOutError,"Timed out."); + default : { + std::ostringstream ostream; + ostream << "Unknown error [" << errno << "]"; + return StandardException(loc, UnknownError, ostream.str()); + } + } + +} + + +} // namespace devices +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_pos.cpp new file mode 100644 index 0000000..c1e2265 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_pos.cpp @@ -0,0 +1,168 @@ +/** + * @file /src/lib/ofile_pos.cpp + * + * @brief Posix synchronous file implementation. + * + * @date September 2009 + **/ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/devices/ofile_pos.hpp" +#include "../../include/ecl/devices/detail/error_handler.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [OFile] +*****************************************************************************/ + +OFile::OFile() : + file(NULL), + error_handler(NoError) +{} + +OFile::OFile(const std::string &file_name, const WriteMode &write_mode) : + file(NULL), + error_handler(NoError) +{ + ecl_try { + open(file_name,write_mode); + } ecl_catch( StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +OFile::~OFile() { + if ( open() ) { + // This flushes and closes the file descriptor. + if ( fclose(file) != 0 ) { + // implement some mechanism if ever needed, but no + // exceptions allowed in destructors, just have to assume the best. + } + file = NULL; + } +} +/***************************************************************************** +** Implementation [OFile][open/close] +*****************************************************************************/ + +bool OFile::open(const std::string &file_name, const WriteMode &write_mode) { + name = file_name; + switch(write_mode) { + case(New) : { + file_descriptor = ::open(name.c_str(), O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH); + if ( file_descriptor == -1 ) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + file = fdopen(file_descriptor,"w"); + break; + } + case(Append) : { + file_descriptor = ::open(name.c_str(),O_WRONLY|O_APPEND|O_CREAT, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH); + if ( file_descriptor == -1 ) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + file = fdopen(file_descriptor,"a"); + break; + } + default : break; + } + if ( file == NULL ) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + error_handler = NoError; + return true; +} + +bool OFile::close() { + if ( open() ) { + // This flushes and closes the file descriptor. + if ( fclose(file) != 0 ) { + ecl_throw(devices::close_exception(LOC,name)); + error_handler = devices::close_error(); + return false; + } + file = NULL; + } + error_handler = NoError; + return true; +} +/***************************************************************************** +** Implementation [OFile][write] +*****************************************************************************/ + +long OFile::write(const char &c) +{ + if ( !open() ) { + ecl_debug_throw(StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(&c,1,1,file); + if ( written <= 0 ) { + ecl_debug_throw(StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + // fwrite returns the number of 'items' written, not bytes! + return written; +} + +long OFile::write(const char* s, unsigned long n) +{ + if ( !open() ) { + ecl_debug_throw(StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(s,n,1,file); + if ( written <= 0 ) { + ecl_debug_throw(StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + // fwrite returns the number of 'items' written, not bytes! + return n*written; +} + +bool OFile::flush() { + // This flushes userland buffers to the kernel buffers...not sure why, + // but you can still read the file in real time, so its good enough and + // thus better than a more expensive fsync here. + int result = fflush(file); + if ( result != 0 ) { + ecl_debug_throw ( StandardException(LOC, UnknownError, std::string("Could not fflush ") + name + std::string("."))); + error_handler = UnknownError; + return false; + } + error_handler = NoError; + return true; +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_w32.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_w32.cpp new file mode 100644 index 0000000..94929ad --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/ofile_w32.cpp @@ -0,0 +1,167 @@ +/** + * @file /src/lib/ofile_w32.cpp + * + * @brief Posix synchronous file implementation. + * + * @date April 2013 + **/ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/devices/ofile_w32.hpp" +#include "../../include/ecl/devices/detail/error_handler.hpp" +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [OFile] +*****************************************************************************/ + +OFile::OFile() : + file(NULL), + error_handler(NoError) +{} + +OFile::OFile(const std::string &file_name, const WriteMode &write_mode) : + file(NULL), + error_handler(NoError) +{ + ecl_try { + open(file_name,write_mode); + } ecl_catch( StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +OFile::~OFile() { + if ( open() ) { + // This flushes and closes the file descriptor. + if ( fclose(file) != 0 ) { + // implement some mechanism if ever needed, but no + // exceptions allowed in destructors, just have to assume the best. + } + file = NULL; + } +} +/***************************************************************************** +** Implementation [OFile][open/close] +*****************************************************************************/ + +bool OFile::open(const std::string &file_name, const WriteMode &write_mode) { + name = file_name; + switch(write_mode) { + case(New) : { + if (_sopen_s(&file_descriptor, name.c_str(), _O_WRONLY | _O_CREAT, _SH_DENYNO, _S_IREAD | _S_IWRITE)) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + file = _fdopen(file_descriptor, "w"); + break; + } + case(Append) : { + if (_sopen_s(&file_descriptor, name.c_str(), _O_WRONLY | _O_APPEND | _O_CREAT, _SH_DENYNO, _S_IREAD | _S_IWRITE)) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + file = _fdopen(file_descriptor, "a"); + break; + } + default : break; + } + if ( file == NULL ) { + ecl_throw(devices::open_exception(LOC,file_name)); + error_handler = devices::open_error(); + return false; + } + error_handler = NoError; + return true; +} + +bool OFile::close() { + if ( open() ) { + // This flushes and closes the file descriptor. + if ( fclose(file) != 0 ) { + ecl_throw(devices::close_exception(LOC,name)); + error_handler = devices::close_error(); + return false; + } + file = NULL; + } + error_handler = NoError; + return true; +} +/***************************************************************************** +** Implementation [OFile][write] +*****************************************************************************/ + +long OFile::write(const char &c) +{ + if ( !open() ) { + ecl_debug_throw(StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(&c,1,1,file); + if ( written <= 0 ) { + ecl_debug_throw(StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + // fwrite returns the number of 'items' written, not bytes! + return written; +} + +long OFile::write(const char* s, unsigned long n) +{ + if ( !open() ) { + ecl_debug_throw(StandardException(LOC, OpenError, std::string("File ") + name + std::string(" is not open for writing."))); + error_handler = OpenError; + return -1; + } + size_t written = fwrite(s,n,1,file); + if ( written <= 0 ) { + ecl_debug_throw(StandardException(LOC, WriteError, std::string("Could not write to ") + name + std::string("."))); + error_handler = WriteError; + return -1; + } + error_handler = NoError; + // fwrite returns the number of 'items' written, not bytes! + return n*written; +} + +bool OFile::flush() { + // This flushes userland buffers to the kernel buffers...not sure why, + // but you can still read the file in real time, so its good enough and + // thus better than a more expensive fsync here. + int result = fflush(file); + if ( result != 0 ) { + ecl_debug_throw ( StandardException(LOC, UnknownError, std::string("Could not fflush ") + name + std::string("."))); + error_handler = UnknownError; + return false; + } + error_handler = NoError; + return true; +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_pos.cpp new file mode 100644 index 0000000..1103b6f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_pos.cpp @@ -0,0 +1,376 @@ +/** + * @file /src/lib/serial_pos.cpp + * + * @brief Posix implementation for serial ports. + * + * @date September 2009 + **/ + +/***************************************************************************** + ** Platform Check + *****************************************************************************/ + +#include +#ifdef ECL_IS_POSIX + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include // div +#include // access +#include +#include +#include "../../include/ecl/devices/serial_pos.hpp" +#include "../../include/ecl/devices/detail/error_handler.hpp" + +/***************************************************************************** + ** Platform Checks + *****************************************************************************/ + +#include +// B921600 baud rate macro is not part of the posix specification (see +// http://digilander.libero.it/robang/rubrica/serial.htm#3_1_1). However +// FreeBSD has had it for at least four years and linux quite some time too. +// Apple Macs however do not currently have it, so we help it here. +#if defined(ECL_IS_APPLE) + #ifndef B460800 + #define B460800 460800 + #endif + #ifndef B921600 + #define B921600 921600 + #endif +#endif + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Using + *****************************************************************************/ + +using std::string; +using ecl::InvalidInputError; +using ecl::OpenError; +using ecl::StandardException; + +/***************************************************************************** + ** Implementation [Serial][C&D] + *****************************************************************************/ + +Serial::Serial(const std::string& port_name, const BaudRate &baud_rate, const DataBits &data_bits, + const StopBits &stop_bits, const Parity &parity) : + port(port_name), read_timeout_ms(5000), error_handler(NoError) +{ + ecl_try + { + open(port_name, baud_rate, data_bits, stop_bits, parity); + } ecl_catch( const StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +Serial::~Serial() +{ + close(); +} + +/***************************************************************************** + ** Implementation [Serial][Open] + *****************************************************************************/ + +bool Serial::open(const std::string& port_name, const BaudRate &baud_rate, const DataBits &data_bits, + const StopBits &stop_bits, const Parity &parity) +{ + + /********************* + ** Input Checks + **********************/ + if (stop_bits == StopBits_15) + { + ecl_throw( + StandardException(LOC,ConfigurationError,"Standard serial device does not accept StopBits_15 as valid (used in ftdi).")); + error_handler = InvalidArgError; + is_open = false; + return false; + } + + if (open()) + { + close(); + } + port = port_name; + // One curious thing here is O_NONBLOCK. If you do not specify this, it will try + // and wait till the line has an 'other' end. Which it can't possibly know, so + // it will effectively block here forever. + file_descriptor = ::open(port_name.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + if (file_descriptor == -1) + { + ecl_throw(devices::open_exception(LOC,port_name)); + error_handler = devices::open_error(); + is_open = false; + return false; + } + + static const int baud_rate_flags[] = {B110, B300, B600, B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, + B230400, B460800, B921600}; + if (baud_rate >= (sizeof(baud_rate_flags) / sizeof(B110))) + { + ecl_throw(StandardException(LOC,ConfigurationError,"Selected baudrate is not supported.")); + error_handler = InvalidArgError; + is_open = false; + return false; + } + static const int data_bits_flags[] = {CS5, CS6, CS7, CS8}; + + /********************* + ** Current Settings + **********************/ +// tcgetattr(file_descriptor,&options); // Need? + /****************************************** + ** Flow Control + *******************************************/ + // Turn off the O_NONBLOCK we set back when opening (we want by default + // blocking and timeouts etc to occur). + // Using 0 as the argument here resets the file status flags to defaults. + fcntl(file_descriptor, F_SETFL, 0); + // this came from ros' hokoyu node code for setting a lock on the device file descriptor + // useful if you want to make sure other devices dont mess with your device! + struct flock file_lock; + file_lock.l_type = F_WRLCK; + file_lock.l_whence = SEEK_SET; + file_lock.l_start = 0; + file_lock.l_len = 0; + file_lock.l_pid = getpid(); + if (fcntl(file_descriptor, F_SETLK, &file_lock) != 0) + { + ecl_throw( + StandardException(LOC,OpenError,std::string("Device is already locked. Try 'lsof | grep ") + port + std::string("' to find other processes that currently have the port open (if the device is a symbolic link you may need to replace the device name with the device that it is pointing to) [posix error in case it is something else: " + std::to_string(errno)))); + error_handler = IsLockedError; + is_open = false; + return false; + } + + /****************************************** + ** Initialise flags + *******************************************/ + options.c_cflag = 0; + options.c_iflag = 0; + options.c_lflag = 0; + options.c_oflag = 0; + + /********************* + ** Baud rates + **********************/ + if (cfsetspeed(&options, baud_rate_flags[baud_rate]) < 0) + { + ecl_throw(StandardException(LOC,ConfigurationError,"Setting speed failed.")); + error_handler = InvalidArgError; + is_open = false; + return false; + } + + /********************* + ** Ownership + **********************/ + /* + * CLOCAL and CREAD should always be set. + * They make sure the owner of the port is + * not changed by the program. + */ + options.c_cflag |= CLOCAL; + options.c_cflag |= CREAD; + + /********************* + ** Disable Flow control + **********************/ +#if defined(CRTSCTS) + options.c_cflag &= ~CRTSCTS; // Disable hardware flow control (old) +#elif defined (CNEW_RTSCTS) + options.c_cflag &= ~CNEW_RTSCTS; // Disable hardware flow control (new) +#endif + + /********************* + ** StopBits + **********************/ + if (stop_bits == StopBits_1) + { + options.c_cflag &= ~CSTOPB; // One stop bit only + } + else + { + options.c_cflag |= CSTOPB; // Two stop bits. + } + + /****************************************** + ** DataBits + *******************************************/ + options.c_cflag &= ~CSIZE; // Mask (i.e. reset) character size bits + options.c_cflag |= data_bits_flags[data_bits]; // Now set the # data bits + + /****************************************** + ** Processing + *******************************************/ + options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // raw, no echoing or waiting till a flush or signals + // options.c_lflag |= (ICANON | ECHO | ECHOE); // like a chat session + + /****************************************** + ** Input Options + *******************************************/ + options.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control + + /****************************************** + ** Output Options + *******************************************/ +// options.c_oflag |= OPOST; // Perform a little post processing +// options.c_oflag |= ONLCR; // Man NL to NL-CR + /********************* + ** Parity + **********************/ + if (parity == NoParity) + { + options.c_cflag &= ~PARENB; // No Parity + } + else if (parity == EvenParity) + { + options.c_iflag |= (INPCK | ISTRIP); // Enable parity check and strip parity bit + options.c_cflag |= PARENB; + options.c_cflag &= ~PARODD; + } + else + { // OddParity + options.c_iflag |= (INPCK | ISTRIP); // Enable parity check and strip parity bit + options.c_cflag |= PARENB; + options.c_cflag |= PARODD; + } + + /****************************************** + ** Enable + ******************************************* + * TCSANOW - make changes immediately + * TCSADRAIN - wait till everything is transmitted, don't do anything with unread data. + * TCSAFLUSH - wait till everything is transmitted, also clear unread data. + *******************************************/ + tcsetattr(file_descriptor, TCSAFLUSH, &options); + + /****************************************** + ** Reset Status + *******************************************/ + if ( read_timeout_ms == NonBlocking ) { + unblock(); + } else { + block(read_timeout_ms); + } + clear(); + + is_open = true; + error_handler = NoError; + return true; +} + +void Serial::close() +{ + if (is_open) + { + // should check return values here, it does have some, EBADF/EINTR/EIO + ::close(file_descriptor); + is_open = false; + } +} + +bool Serial::open() +{ + if ( is_open ) { + if ( access(port.c_str(), F_OK ) == -1 ) { + close(); + } + } + return is_open; +} + +/***************************************************************************** + ** Implementation [Serial][Reading Modes] + *****************************************************************************/ + +void Serial::block(const unsigned long &timeout) +{ + if (timeout < 100) + { + if (timeout < 5) + { + fake_snooze.period(ecl::Duration(0.001)); + fake_loop_count = timeout; + } + else if (timeout < 20) + { + fake_snooze.period(ecl::Duration(0.002)); + div_t d = div(timeout, 2); + if (d.rem == 0) + { + fake_loop_count = d.quot; + } + else + { + fake_loop_count = d.quot + 1; + } + } + else + { + fake_snooze.period(ecl::Duration(0.005)); + div_t d = div(timeout, 5); + if (d.rem == 0) + { + fake_loop_count = d.quot; + } + else + { + fake_loop_count = d.quot + 1; + } + } + this->unblock(); + } + else + { + options.c_cc[VMIN] = 0; + // VTIME is in tenths of a second + if (timeout < 100) + { // just in case we're not running in debug mode or exceptions are disabled. + options.c_cc[VTIME] = static_cast(1); // 100/100 + } + else + { + options.c_cc[VTIME] = static_cast(timeout / 100); + } + tcsetattr(file_descriptor, TCSAFLUSH, &options); + } + read_timeout_ms = timeout; +} + +void Serial::unblock() +{ + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + tcsetattr(file_descriptor, TCSAFLUSH, &options); + read_timeout_ms = NonBlocking; +} + +/***************************************************************************** + ** Implementation [Serial][Reading] + *****************************************************************************/ +long Serial::remaining() +{ + long bytes = 0; + ioctl(file_descriptor, FIONREAD, &bytes); + return bytes; +} + +} // namespace ecl +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_w32.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_w32.cpp new file mode 100644 index 0000000..760d849 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/serial_w32.cpp @@ -0,0 +1,388 @@ +/** + * @file /ecl_devices/src/lib/serial_w32.cpp + * + * @brief Win32 implementation for serial ports. + * + * @date May 2010 + **/ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#ifdef ECL_IS_WIN32 + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/devices/serial_w32.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Serial][C&D] +*****************************************************************************/ + +Serial::Serial(const std::string& port_name, const BaudRate &baud_rate, const DataBits &data_bits, + const StopBits &stop_bits, const Parity &parity ) throw(StandardException) : + port(port_name), is_run(false), file_descriptor(INVALID_HANDLE_VALUE) +{ + try { + open(port_name, baud_rate, data_bits, stop_bits, parity); + } catch ( StandardException &e ) { + throw StandardException(LOC,e); + } +} + +Serial::~Serial() { + close(); +} + +/***************************************************************************** +** Implementation [Serial][Open] +*****************************************************************************/ + +void Serial::open(const std::string& port_name, const BaudRate &baud_rate, const DataBits &data_bits, + const StopBits &stop_bits, const Parity &parity ) throw(StandardException) { + + if ( open() ) { + close(); + } + + if (strstr(port_name.c_str(), "\\\\.\\")) + port = port_name; + else + port = std::string("\\\\.\\") + port_name; + + /****************************************** + * Reset Timeouts + ******************************************/ + m_osRead.Offset = 0; + m_osRead.OffsetHigh = 0; + if (! (m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { + throw StandardException(LOC, OpenError, "Serial port failed to open - could not configure offsets."); + } + m_osWrite.Offset = 0; + m_osWrite.OffsetHigh = 0; + if (! (m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { + throw StandardException(LOC, OpenError, "Serial port failed to open - could not configure offsets."); + } + + /****************************************** + * Open the port handle + ******************************************/ + /* + * CreateFileA is the ascii function. CreateFileW is the unicode function. + * FILE_FLAG_OVERLAPPED - do not block operations (use events to return) + * If the above flag is not specified, it defaults to non-overlapped mode. + * When in non-overlapped mode you can't sit in a thread trying to read the + * port and simultaneously try to write from another. + */ + file_descriptor = CreateFileA( port.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, // Serial ports already exist + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + + /****************************************** + * Open - error handling + ******************************************/ + if (file_descriptor == INVALID_HANDLE_VALUE ) { + int error = GetLastError(); + switch (error) { + case (ERROR_PATH_NOT_FOUND) : { + throw StandardException(LOC,NotFoundError); + break; + } + case (ERROR_FILE_NOT_FOUND) : { + throw StandardException(LOC,NotFoundError); + break; + } + default : { + throw StandardException(LOC,OpenError); + } + } + } + + /****************************************** + ** Configuration + *******************************************/ + static const int baud_rate_flags[] = { CBR_110, CBR_300, CBR_600, CBR_1200, CBR_2400, CBR_4800, CBR_9600, CBR_19200, CBR_38400, CBR_57600, CBR_115200 }; + static const int stop_bits_flags[] = { ONESTOPBIT, TWOSTOPBITS }; // Windoze has a ONE5STOPBITS as well + static const int parity_types_flags[] = { NOPARITY, ODDPARITY, EVENPARITY }; // There are others but we dont need + static const int data_bits_flags[] = { 5, 6, 7, 8 }; + + /****************************************** + * Initialise events to monitor + ******************************************/ + // EV_RXCHAR : A character was received and placed in the input buffer. + SetCommMask( file_descriptor, EV_RXCHAR ); + + /****************************************** + * Initialise the input/output buffer's size + ******************************************/ + SetupComm( file_descriptor, 2048, 2048 ); // 4096,4096 + + /****************************************** + * Clear + ******************************************/ + PurgeComm( file_descriptor, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR ); + + /****************************************** + * Dont care about write timeouts (could be dangerous!?) + ******************************************/ + COMMTIMEOUTS timeouts; + GetCommTimeouts( file_descriptor, &timeouts ); + timeouts.WriteTotalTimeoutMultiplier = 0; + timeouts.WriteTotalTimeoutConstant = 0; + SetCommTimeouts( file_descriptor, &timeouts ); + + /****************************************** + * Setup the Configuration Structure + ******************************************/ + DCB dcb; + + FillMemory(&dcb, sizeof(dcb), 0); + + // MS recommends just grabbing the current state and modifying the required parameters on the + // off chance the structure may change in the future. + if ( !GetCommState( file_descriptor, &dcb) ) { + throw StandardException(LOC,ConfigurationError,"There was an error retrieving the state of the port."); + }; + + /****************************************** + * Protocol Configuration + ******************************************/ + dcb.DCBlength = sizeof(dcb); + dcb.BaudRate = baud_rate_flags[baud_rate]; + dcb.ByteSize = data_bits_flags[data_bits]; + dcb.Parity = parity_types_flags[parity]; + dcb.StopBits = stop_bits_flags[stop_bits]; + dcb.fNull= FALSE; // If true, discard null bytes if they are received + + // dcb.fAbortOnError = TRUE; // Need? + + /****************************************** + * Flow Control + ******************************************/ + dcb.fInX = FALSE; // XON/XOFF flow control during reception. + dcb.fOutX = FALSE; // XON/XOFF flow control during transmission. + dcb.fDtrControl = DTR_CONTROL_DISABLE; // Data-Terminal-Ready flow control + dcb.fRtsControl = RTS_CONTROL_DISABLE; // Request-To-Send flow control. + + dcb.fOutxCtsFlow = FALSE; // don't monitor the Clear-To-Send output flow control signal. + dcb.fOutxDsrFlow = FALSE; // don't monitor the Data-Set-Ready output flow control signal. + + // dcb.XonLim = 1000; // Number of bytes in the input buffer before flow control is activated to inhibit the sender. + // dcb.XoffLim = 1000; // Similar situation as above... + // dcb.XonChar = ASCII_XON; + // dcb.XoffChar = ASCII_XOFF; + + /****************************************** + * Save and Handle Errors + ******************************************/ + if (!SetCommState( file_descriptor, &dcb)) { + int error = GetLastError(); + switch ( error ) { + case ( ERROR_INVALID_PARAMETER ) : { + throw StandardException(LOC,ConfigurationError,"A parameter was configured incorrectly (ERROR_INVALID_PARAMETER)."); + break; + } + default: { + throw StandardException(LOC,ConfigurationError); + break; + } + } + } + + /****************************************** + * Prepare thread for receiving event generated by communication port + ******************************************/ + is_run = true; + event_receiver.cancel(); + event_receiver.start(generateFunctionObject(event_proc, this)); + + block(5000); + is_open = true; +} + +void Serial::close() { + if ( open() ) { + + // release thread for receiving event + is_run = false; + event_receiver.join(); + event_receiver.cancel(); + + if (file_descriptor != INVALID_HANDLE_VALUE) { + // These return values, but assume it works ok, not really critical. + SetCommMask(file_descriptor, 0); + PurgeComm(file_descriptor, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR ); + CloseHandle(file_descriptor); + file_descriptor = INVALID_HANDLE_VALUE; + } + + is_open = false; + } +} + +/***************************************************************************** +** Implementation [Serial][Threading Procedure] +*****************************************************************************/ +void event_proc(void* arg) { + Serial* owner = (Serial*)arg; + if (!owner) + return; + while (owner->is_run) { + DWORD mask; + if (!WaitCommEvent(owner->file_descriptor, &mask, NULL)) { + if (0x000003e3 == GetLastError()) { + break; + } + } + } + owner->file_descriptor = INVALID_HANDLE_VALUE; + owner->is_open = false; +} + +/***************************************************************************** +** Implementation [Serial][Writing] +*****************************************************************************/ + +long Serial::write(const char &c) { + return write(&c, 1); +} + +long Serial::write(const char *s, unsigned long n) { + DWORD written, error, error_flags; + COMSTAT comstat; + int result; + + result = WriteFile( file_descriptor, s, n, &written, &m_osWrite); + + if (!result) { + if (GetLastError() == ERROR_IO_PENDING) { + while (!GetOverlappedResult(file_descriptor, &m_osWrite, &written, TRUE)) { + error = GetLastError(); + if (error != ERROR_IO_INCOMPLETE) { + ClearCommError( file_descriptor, &error_flags, &comstat); + break; + } + } + } else { + written = 0; + ClearCommError(file_descriptor, &error_flags, &comstat); + } + } + ecl_assert_throw( written != 0, StandardException(LOC,WriteError) ); + return written; +} + +/***************************************************************************** +** Implementation [Serial][Reading Modes] +*****************************************************************************/ + +void Serial::block(const long &timeout) { + + ecl_assert_throw( timeout >= 0, StandardException(LOC, InvalidInputError, "Serial port timeouts must be greater than 0ms.") ); + COMMTIMEOUTS timeouts; + GetCommTimeouts( file_descriptor, &timeouts ); + + // See http://msdn2.microsoft.com/en-us/library/ms885171.aspx for details + // about this combination of settings. + timeouts.ReadIntervalTimeout = MAXDWORD; + timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; + timeouts.ReadTotalTimeoutConstant = static_cast(timeout); + SetCommTimeouts( file_descriptor, &timeouts ); +} + +void Serial::unblock() { + COMMTIMEOUTS timeouts; + GetCommTimeouts( file_descriptor, &timeouts ); + + // See http://msdn2.microsoft.com/en-us/library/ms885171.aspx for details + // about this combination of settings. + timeouts.ReadIntervalTimeout = MAXDWORD; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 0; + SetCommTimeouts( file_descriptor, &timeouts ); +} + +/***************************************************************************** +** Implementation [Serial][Reading] +*****************************************************************************/ +long Serial::remaining() { + unsigned long error; + _COMSTAT status; + if ( ClearCommError(file_descriptor,&error,&status) ) { + return status.cbInQue; + } else { + return -1; + } +} + +long Serial::read(char &c) { + return read(&c,1); +} + +long Serial::read(char *s, const unsigned long &n) +{ + COMSTAT comstat; + DWORD read=0, error, error_flags; + DWORD dwRes; + + /********************* + ** Windows Hack + **********************/ + // If its blocking for a minimum number of characters, + /********************* + ** Reading Serial + **********************/ + if (file_descriptor == INVALID_HANDLE_VALUE) { + return 0; + } + + if (!ReadFile( file_descriptor, s, n, &read, &m_osRead) ) { + error = GetLastError(); + + if( error != ERROR_IO_PENDING ) { + if (error != ERROR_ACCESS_DENIED) + ClearCommError(file_descriptor, &error_flags, &comstat); + + return 0; + } else { + dwRes = WaitForSingleObject( m_osRead.hEvent, INFINITE ); + + switch( dwRes ) { + case WAIT_OBJECT_0: + if( !GetOverlappedResult( file_descriptor, &m_osRead, &read, FALSE) ) { + ClearCommError(file_descriptor, &error_flags, &comstat); + return 0; + } else { + ClearCommError(file_descriptor, &error_flags, &comstat); + return read; + } + break; + default: + { + ClearCommError(file_descriptor, &error_flags, &comstat); + return 0; + } + break; + } + } + } + return read; +} +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/shared_file.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/shared_file.cpp new file mode 100644 index 0000000..a5c2e19 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/shared_file.cpp @@ -0,0 +1,219 @@ +/** + * @file /src/lib/shared_file_pos.cpp + * + * @brief Posix shared file implementation. + * + * @date November 2009 + **/ +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ +// Only because there is only ofile_pos support so far. + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "../../include/ecl/devices/shared_file.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { + +/**************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::WriteMode; +using ecl::CloseError; +using ecl::StandardException; +using ecl::Mutex; + +/***************************************************************************** +** Implementation [SharedFileCommon] +*****************************************************************************/ + +SharedFileCommon::SharedFileCommon(const std::string &name, ecl::WriteMode mode) : + count(1), + error_handler(NoError) +{ + ecl_try { + if ( !file.open(name,mode) ) { + error_handler = file.error(); + } + } ecl_catch( StandardException &e ) { + error_handler = file.error(); + ecl_throw(StandardException(LOC,e)); + } +} + +/***************************************************************************** +** Static Variable Initialisation [SharedFileManager] +*****************************************************************************/ + +Mutex SharedFileManager::mutex; +std::map SharedFileManager::opened_files; + +/***************************************************************************** +** Implementation [SharedFileManager] +*****************************************************************************/ + +SharedFileCommon* SharedFileManager::RegisterSharedFile(const std::string& name, ecl::WriteMode mode) { + + mutex.lock(); + std::map::iterator iter = opened_files.find(name); + SharedFileCommon* shared_instance; + if ( iter != opened_files.end() ) { + /****************************************** + ** File exists - do not open + *******************************************/ + iter->second->count += 1; + shared_instance = iter->second; + } else { + /****************************************** + ** File does not exist - open it + *******************************************/ + ecl_try { + shared_instance = new SharedFileCommon(name,mode); + opened_files.insert(std::pair(name,shared_instance)); + } ecl_catch ( StandardException &e ) { + shared_instance = NULL; + ecl_throw(StandardException(LOC,e)); + } + } + mutex.unlock(); + return shared_instance; +} +/** + * Don't have to worry about this too much, its only called when closing. + * @param name + * @return + */ +bool SharedFileManager::DeRegisterSharedFile(const std::string& name) { + + mutex.lock(); + std::map::iterator iter = opened_files.find(name); + + if ( iter == opened_files.end() ) { + ecl_throw(StandardException(LOC,CloseError,"The specified shared object file could not be closed - was not found.")); + return false; + } + if ( iter->second->count == 1 ) { + delete iter->second; + opened_files.erase(iter); + } else { + iter->second->count -= 1; + } + mutex.unlock(); + return true; +} + +} // namespace devices + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; + +/***************************************************************************** +** Implementation [SharedFile] +*****************************************************************************/ + +SharedFile::SharedFile(const std::string &name, WriteMode mode) : + shared_instance(NULL) +{ + ecl_try { + open(name,mode); + } ecl_catch( StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +SharedFile::~SharedFile() { + ecl_try { + if (shared_instance->error_handler.flag() == NoError) { + devices::SharedFileManager::DeRegisterSharedFile( shared_instance->file.filename() ); + } else { + delete shared_instance; + } + } ecl_catch( StandardException &e ) { + // Never throw from a destructor! + // use some other mechanism!!! + // throw StandardException(LOC,e); + } +} + +bool SharedFile::open(const std::string &name, WriteMode mode) { + ecl_try { + shared_instance = devices::SharedFileManager::RegisterSharedFile(name,mode); + if ( shared_instance == NULL ) { + shared_instance = new devices::SharedFileCommon(); + shared_instance->error_handler = OpenError; + return false; + } else { + shared_instance->error_handler = NoError; + return true; + } + } ecl_catch ( StandardException &e ) { + shared_instance = new devices::SharedFileCommon(); + shared_instance->error_handler = OpenError; + ecl_throw(StandardException(LOC,e)); + } +} + +long SharedFile::write(const char &c) { + long n = buffer.append(c); + if ( buffer.full() ) { + if ( !flush() ) { + return -1; + } + } + return n; +} + +long SharedFile::write(const char* s, unsigned long n) { + unsigned int no_written = 0; + while ( no_written < n ) { + no_written += buffer.append(s+no_written,n-no_written); + if ( buffer.full() ) { + if ( !flush() ) { + return -1; + } + } + } + return n; +} + +bool SharedFile::flush() { + long written; + ecl_debug_try { + written = shared_instance->file.write(buffer.c_ptr(), buffer.size() ); + } ecl_debug_catch(const StandardException &e) { + shared_instance->error_handler = shared_instance->file.error(); + ecl_debug_throw(StandardException(LOC,e)); + } + buffer.clear(); + // fallback for no exceptions + shared_instance->error_handler = shared_instance->file.error(); + if ( written > 0 ) { + return true; + } else { + return false; + } +} + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_client_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_client_pos.cpp new file mode 100644 index 0000000..14d0cd3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_client_pos.cpp @@ -0,0 +1,241 @@ +/** + * @file /src/lib/socket_client_pos.cpp + * + * @brief Posix implementation for tcp/ip clients. + * + * @date January 2009 + **/ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include // gethostbyname +#include +#include "../../include/ecl/devices/detail/socket_error_handler_pos.hpp" +#include "../../include/ecl/devices/detail/socket_exception_handler_pos.hpp" +#include "../../include/ecl/devices/socket_connection_status.hpp" +#include "../../include/ecl/devices/socket_client_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +SocketClient::SocketClient(const std::string &host_name, const unsigned int &port_number) : + hostname(host_name), + port(port_number), + is_open(false), + error_handler(NoError) +{ + ecl_try { + open(host_name, port_number); + } ecl_catch ( StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +void SocketClient::close() { + is_open = false; + ::close(socket_fd); // should have error handling here +} + +bool SocketClient::open( const std::string &host_name, const unsigned int& port_number ) { + + if ( this->open() ) { this->close(); } + hostname = host_name; + port = port_number; + + /********************* + * Open + ********************** + * PF_INET (IP4), PF_LOCAL (LOCALHOST) + * SOCK_STREAM (TCPIP), SOCK_DGRAM (UDP), SOCK_RAW + * Last argument is generally always 0 (sub-type) + */ + // maybe hostname == localhost or 127.0.0.1 -> use PF_LOCAL? + socket_fd = socket(AF_INET, SOCK_STREAM, 0); +// socket_fd = socket(PF_INET, SOCK_STREAM, 0); + if ( socket_fd == -1 ) { + ecl_throw(devices::socket_exception(LOC)); + error_handler = devices::socket_error(); + return false; + } + /********************* + ** Hostname + **********************/ + struct hostent *host_entry; + /****************************************** + * struct hostent { + * char *h_name; //official name of host + * char **h_aliases; // array of aliases (terminated by NULL) + * int h_addrtype; // host address type + * int h_length; // length of address + * char **h_addr_list; // array of addresses (terminated by NULL) + * } + ******************************************/ + host_entry = gethostbyname(hostname.c_str()); + if ( host_entry == NULL ) { // gethostbyname doesn't seem to be checking hostname validity??? + ::close(socket_fd); + ecl_throw(devices::gethostbyname_exception(LOC,hostname)); + error_handler = devices::gethostbyname_error(); + return false; + } + + /********************* + ** Socket Details + **********************/ + struct sockaddr_in destination; + destination.sin_family = AF_INET; // host byte order + destination.sin_addr = *((struct in_addr *)host_entry->h_addr); + destination.sin_port = htons(port); // short host byte order to network byte order + memset(destination.sin_zero, '\0', sizeof destination.sin_zero); + + /********************* + ** Connect + **********************/ + int connect_result = connect( socket_fd, (struct sockaddr *) &destination, sizeof(destination) ); + if ( connect_result == -1 ) { + is_open = false; + ::close(socket_fd); + ecl_throw(devices::connection_exception(LOC)); + error_handler = devices::connection_error(); + return false; + } + is_open = true; + error_handler = NoError; + return true; +} + +/***************************************************************************** +** Implementation [SocketClient][Source] +*****************************************************************************/ + +long SocketClient::read(char &c) { + return read(&c,1); +} + +long SocketClient::read(char *s, const unsigned long &n) { + + if ( !open() ) { + return ConnectionDisconnected; + } + + /********************* + * Check Status + *********************/ +// SocketStatus status = pollStatus(POLLIN); // Times out according to timeout_ms if it can't read in the specified time. +// std::cout << "Polling Status " << status << std::endl; +// if ( status != SocketReadReady ) { return status; } // else it is ok to write. + + int bytes_read = ::recv(socket_fd, s, n, 0); // Consider using MSG_WAITALL + + /********************* + ** Error Handling + **********************/ + if ( bytes_read == 0 ) { + // Server has dropped + close(); + return ConnectionHungUp; + } + if ( bytes_read < 0 ) { + if ( errno == ECONNRESET ) { + close(); + return ConnectionHungUp; + } else { + ecl_debug_throw( devices::receive_exception(LOC) ); + error_handler = devices::receive_error(); + return ConnectionProblem; + } + } + error_handler = NoError; + return bytes_read; +} + +long SocketClient::peek(char *s, const unsigned long &n) { + + if ( !open() ) { return ConnectionDisconnected; } + + int bytes_read = ::recv(socket_fd, s, n, MSG_PEEK); + if ( bytes_read < 0 ) { + ecl_debug_throw( devices::receive_exception(LOC) ); + error_handler = devices::receive_error(); + return ConnectionProblem; + } + error_handler = NoError; + return bytes_read; +} + +long SocketClient::remaining() { + + if ( !open() ) { return ConnectionDisconnected; } + + unsigned long bytes; + int result = ioctl(socket_fd, FIONREAD, &bytes); + if ( result == -1 ) { + ecl_debug_throw( devices::ioctl_exception(LOC) ); + error_handler = devices::ioctl_error(); + } + error_handler = NoError; + return bytes; +} + +/***************************************************************************** +** Implementation [SocketClient][Sink] +*****************************************************************************/ + +long SocketClient::write(const char &c) { + + return write(&c, 1); +} + +long SocketClient::write(const char *s, unsigned long n) { + + if ( !open() ) { return ConnectionDisconnected; } + + /********************* + * Write + *********************/ + int bytes_written = ::send(socket_fd,s,n,MSG_NOSIGNAL); + + if ( bytes_written < 0 ) { + switch(errno) { + case ( EPIPE ) : { + close(); + return ConnectionHungUp; + } + default : { + ecl_debug_throw( devices::send_exception(LOC) ); + error_handler = devices::send_error(); + return ConnectionProblem; + } + } + } + return bytes_written; +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_server_pos.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_server_pos.cpp new file mode 100644 index 0000000..8271b69 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/socket_server_pos.cpp @@ -0,0 +1,200 @@ +/** + * @file /src/lib/socket_server_pos.cpp + * + * @brief Posix implementation for tcp/ip servers. + * + * @date January 2009 + **/ + +/***************************************************************************** +** Cross platform +*****************************************************************************/ + +#include +#ifndef ECL_IS_APPLE +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/devices/socket_connection_status.hpp" +#include "../../include/ecl/devices/socket_server_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [SocketServer] +*****************************************************************************/ + +SocketServer::SocketServer(const unsigned int &port_number) : + port(port_number), + is_open(false), + error_handler(NoError) +{ + ecl_try { + open(port_number); + } ecl_catch ( const StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } +} + +bool SocketServer::open( const unsigned int& port_number ) { + + if ( this->open() ) { this->close(); } + port = port_number; + + /************************************************************************* + * Open socket + ************************************************************************* + * PF_INET (IP4), PF_LOCAL (LOCALHOST) + * SOCK_STREAM (TCPIP), SOCK_DGRAM (UDP), SOCK_RAW + * Last argument is generally always 0 (sub-type) + */ + socket_fd = socket(AF_INET, SOCK_STREAM, 0); +// socket_fd = socket(PF_INET, SOCK_STREAM, 0); + if ( socket_fd == -1 ) { + ecl_throw(devices::socket_exception(LOC)); + error_handler = devices::socket_error(); + return false; + } + + /************************************************************************* + * Configure Socket Details + ************************************************************************/ + // allow *immediate* socket reuse, http://www.ibm.com/developerworks/library/l-sockpit/ + int on; + on = 1; + setsockopt( socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ); + // other options + struct sockaddr_in server; + server.sin_family = AF_INET; // host byte order + server.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP + server.sin_port = htons(port); // short host byte order to network byte order + memset(server.sin_zero, '\0', sizeof server.sin_zero); // zero the server structure + + /************************************************************************* + * Bind address to the socket + ************************************************************************/ + int bind_result = bind(socket_fd, (struct sockaddr *) &server, sizeof(server)); + if ( bind_result == - 1 ) { + is_open = true; + ecl_throw(devices::bind_exception(LOC)); + error_handler = devices::bind_error(); + return false; + } + is_open = true; + error_handler = NoError; + return true; +} + +int SocketServer::listen() { + + /********************* + ** Params + **********************/ + ::listen(socket_fd,1); // Number of clients to allow + + /********************* + ** Listen + **********************/ + struct sockaddr_in client; + int client_length = sizeof(client); + + client_socket_fd = accept(socket_fd, (struct sockaddr *) &client, (socklen_t *) &client_length); + if (client_socket_fd < 0) { + ecl_throw(devices::accept_exception(LOC)); + error_handler =devices::accept_error(); + return -1; + } + error_handler = NoError; + return client_socket_fd; + +} + +/***************************************************************************** +** Implementation [SocketServer][Source] +*****************************************************************************/ + +long SocketServer::read(char *s, const unsigned long &n) { + + if ( !open() ) { return ConnectionDisconnected; } + + int bytes_read = ::recv(client_socket_fd, s, n, 0); + if ( bytes_read < 0 ) { + ecl_debug_throw(devices::receive_exception(LOC)); + error_handler = devices::receive_error(); + return ConnectionProblem; + } + + if ( bytes_read == 0 ) { + // Server has dropped + close(); + return ConnectionHungUp; + } + error_handler = NoError; + return bytes_read; +} + +long SocketServer::peek(char *s, const unsigned long &n) { + + int bytes_read = ::recv(client_socket_fd, s, n, MSG_PEEK); + if ( bytes_read < 0 ) { + ecl_debug_throw(devices::receive_exception(LOC)); + error_handler = devices::receive_error(); + return ConnectionProblem; + } + error_handler = NoError; + return bytes_read; +} + +long SocketServer::remaining() { + unsigned long bytes; + int result = ioctl(client_socket_fd, FIONREAD, &bytes); + if ( result == -1 ) { + ecl_debug_throw(devices::ioctl_exception(LOC)); + error_handler = devices::ioctl_error(); + return ConnectionProblem; + } + error_handler = NoError; + return bytes; +} + + +/***************************************************************************** +** Implementation [SocketServer][Sink] +*****************************************************************************/ + +long SocketServer::write(const char *s, unsigned long n) { + #ifdef MSG_NOSIGNAL + int bytes_written = ::send(client_socket_fd,s,n,0|MSG_NOSIGNAL); + #else + int bytes_written = ::send(client_socket_fd,s,n,0); + #endif + if ( bytes_written < 0 ) { + switch(errno) { + case ( EPIPE ) : { + close(); + return ConnectionHungUp; + } + default : { + ecl_debug_throw( devices::send_exception(LOC) ); + error_handler = devices::send_error(); + return ConnectionProblem; + } + } + } + error_handler = NoError; + return bytes_written; +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* !ECL_IS_APPLE */ diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/lib/string.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/lib/string.cpp new file mode 100644 index 0000000..7ae0e19 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/lib/string.cpp @@ -0,0 +1,166 @@ +/** + * @file /src/lib/string.cpp + * + * @brief Implementation of a virtual string device. + * + * @date December 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/devices/string.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [String] +*****************************************************************************/ +String::String(const char* str) +{ + buffer_length = strlen(str) + 1; + buffer = new char[buffer_length]; // Need +1 so we can attach \0 to produce c_str() + memcpy(buffer,str,buffer_length-1); + buffer_cur_write = buffer + buffer_length - 1; + buffer_cur_read = buffer; +} +String::~String() { + delete [] buffer; +} +const char* String::c_str() { + *buffer_cur_write = '\0'; // Null terminate + return buffer; +} +std::string String::str() { + std::string s; + s.assign(buffer,size()); + return s; +} + +void String::grow(int no_bytes) { + char* new_buffer; + unsigned long cur_pos = buffer_cur_read - buffer; + unsigned long cur_end = buffer_cur_write - buffer; + new_buffer = new char[size()+no_bytes+1]; + memcpy(new_buffer,buffer,size()); + delete [] buffer; + buffer = new_buffer; + buffer_cur_read = buffer+cur_pos; + buffer_cur_write = buffer+cur_end; +} + +/***************************************************************************** +** Implementation [String][Source Interface] +*****************************************************************************/ +long String::read(char &c) { + if ( remaining() != 0 ) { + c = *buffer_cur_read; + ++buffer_cur_read; + return 1; + } else { + return 0; + } +} +/** + * Read a character string from the buffer. + * @param s : points to the beginning of the character string + * @param n : the number of characters to read + * @return long : number of characters read, negative on error. + **/ +long String::read(char* s, unsigned long n) +{ + unsigned long rem = remaining(); + + if ( rem > n ) { + memcpy(s,buffer_cur_read,n); + buffer_cur_read += n; + return n; + } else if ( rem != 0 ) { + memcpy(s,buffer_cur_read,rem); + buffer_cur_read += rem; + return rem; + } else { // rem = 0; + return 0; + } +} +/** + * Remaining bytes (from the pointer's current position in the + * buffer until its end). + * @return unsigned long : remaining bytes in the string's buffer. + **/ +unsigned long String::remaining() +{ + return buffer_cur_write - buffer_cur_read; +} + +/** + * Clear the contents of the string device (clears and + * deletes the buffer). + **/ +void String::clear() +{ + delete [] buffer; + buffer = new char[1]; + buffer_length = 0; + buffer_cur_write = buffer; + buffer_cur_read = buffer; +} + +/***************************************************************************** +** Implementation [String][Sink Interface] +*****************************************************************************/ +/** + * Write a character to the buffer - we always append. + * @param c : the character. + * @return long : number of characters written, negative on error. + **/ +long String::write(char c) +{ + // Remember that the last position in the buffer is for the char string terminator + if ( buffer_cur_write-buffer == static_cast(buffer_length) -1) { + grow(); + } + *buffer_cur_write = c; + ++buffer_cur_write; + return 1; +} +/** + * Write a character string to the buffer - we always append. + * @param s : points to the beginning of the character string + * @param n : the number of characters to write. + * @return long : number of characters written, negative on error. + **/ +long String::write(const char* s, unsigned long n) +{ + // Remember that the last position in the buffer is for the char string terminator + if ( buffer_cur_write-buffer > static_cast(buffer_length) - 1 - static_cast(n) ) { + grow(n+256); + } + memcpy(buffer_cur_write,s,n); + buffer_cur_write += n; + return n; +} + + +/***************************************************************************** +** Implementation [String][Seekable Interface] +*****************************************************************************/ +/** + * Size of the string (bytes). + * @return long : string size (bytes) + **/ +unsigned long String::size() +{ + return buffer_cur_write - buffer; +} + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_devices/src/test/CMakeLists.txt new file mode 100644 index 0000000..d028e59 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/test/CMakeLists.txt @@ -0,0 +1,28 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_devices_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_containers::ecl_containers + ecl_errors::ecl_errors + ecl_mpl::ecl_mpl + ecl_threads::ecl_threads + ecl_type_traits::ecl_type_traits + ecl_utilities::ecl_utilities + ) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_devices_add_gtest(shared_files) +ecl_devices_add_gtest(files) + + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/test/files.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/test/files.cpp new file mode 100644 index 0000000..0f491b8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/test/files.cpp @@ -0,0 +1,98 @@ +/** + * @file /src/test/files.cpp + * + * @brief Unit Test for the file devices. + * + * @date August 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "../../include/ecl/devices/detail/character_buffer.hpp" +#include "../../include/ecl/devices/ofile.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Append; +using ecl::devices::CharStringBuffer; +using ecl::New; +using ecl::OFile; +using ecl::StandardException; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(FilesTests,construct) { + + bool result = true; + try { + OFile o_file1("odude.txt",New); + OFile o_file2; + o_file2.open("odude2.txt",New); + } catch ( const StandardException& e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(FilesTests,write) { + OFile o_file1("odude.txt",New); + OFile o_file2; + o_file2.open("odude2.txt",New); + long n; + n = o_file1.write("Heya Dude\n",10); + o_file1.flush(); + EXPECT_EQ(10,n); + n = o_file2.write("Heya Dude\n",10); + o_file2.flush(); + EXPECT_EQ(10,n); + std::string heya_dude("Heya Dude From Array\n"); + ecl::Array buffer; + std::copy(heya_dude.begin(), heya_dude.end(), buffer.begin()); + n = o_file2.write(buffer.stencil(0,heya_dude.size())); + o_file2.flush(); + EXPECT_EQ(21,n); +// This is an interesting test of the buffer which sometimes gets autoflushed +// for ( unsigned int i = 0; i < CharStringBuffer::buffer_size/10 + 1; ++i ) { +// o_file1.write("Heya Dude\n",10); +// o_file1.flush(); +// o_file2.write("Heya Dude\n",10); +// o_file2.flush(); +// } +} + +TEST(FilesTests,append) { + OFile o_file("odude.txt",Append); + long n; + n = o_file.write("Appending Dude\n",15); + EXPECT_EQ(15,n); + EXPECT_TRUE( o_file.flush()); +} + +TEST(FilesTest,isOpen) { + OFile o_file1("odude2.txt",Append); + EXPECT_TRUE( o_file1.open()); + OFile o_file2; + EXPECT_FALSE( o_file2.open()); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_devices/src/test/shared_files.cpp b/ros2_ws/src/ecl_core/ecl_devices/src/test/shared_files.cpp new file mode 100644 index 0000000..bb23d50 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_devices/src/test/shared_files.cpp @@ -0,0 +1,80 @@ +/** + * @file /src/test/shared_files.cpp + * + * @brief Unit Test for shared files. + * + * @date November 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/devices/shared_file.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::New; +using ecl::SharedFile; +using ecl::Thread; + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace devices { +namespace tests { + +/***************************************************************************** +** Globals +*****************************************************************************/ + +void shared_files_f() { + SharedFile file("shared.txt"); + long n; + for (unsigned int i = 0; i < 3; ++i ) { + n = file.write("Thread\n",7); + EXPECT_EQ(7,n); + } + file.flush(); +} + + +} // namespace tests +} // namespace devices +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::devices::tests; + +TEST(SharedFileTests,allEggsInTheBasket) { + + SharedFile file("shared.txt"); + Thread thread(shared_files_f); + long n; + for (unsigned int i = 0; i < 3; ++i ) { + n = file.write("Main\n",5); + EXPECT_EQ(5,n); + } + file.flush(); + thread.join(); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_eigen/.cproject b/ros2_ws/src/ecl_core/ecl_eigen/.cproject new file mode 100644 index 0000000..863c87f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/.cproject @@ -0,0 +1,460 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/.project b/ros2_ws/src/ecl_core/ecl_eigen/.project new file mode 100644 index 0000000..9874df5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/.project @@ -0,0 +1,79 @@ + + + ecl_eigen + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_eigen/CHANGELOG.rst new file mode 100644 index 0000000..9fb17a8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/CHANGELOG.rst @@ -0,0 +1,22 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +0.61.16 (2017-01-13) +-------------------- +* find Eigen3 instead of Eigen (that is deprecating) + +0.61.0 (2014-09-12) +------------------- +* internal eigen support for v3.2.1 +* bugfix missing unsupported modules in the install space. + +0.60.9 (2014-04-09) +------------------- +* transfer eigen hunting to ros cmake modules + +0.60.7 (2014-02-03) +------------------- +* export devel prefix include path to ensure configured headers are found. +* export local header directory. + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_eigen/CMakeLists.txt new file mode 100644 index 0000000..207f48c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/CMakeLists.txt @@ -0,0 +1,82 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_eigen) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) + +############################################################################## +# Internal vs External Eigen +############################################################################## + +# Internal eigen logic is quite broken since ament, surgically removed for now +# Leaving the infrastructure in place though, in case we should need to make +# use of it again + +find_package(Eigen3) + +############################################################################## +# Project Configuration +############################################################################## + +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/include) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/include/ecl/eigen.hpp.in + ${PROJECT_BINARY_DIR}/include/ecl/eigen.hpp +) + +install( + FILES ${PROJECT_BINARY_DIR}/include/ecl/eigen.hpp + DESTINATION include/ecl +) + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + Eigen3::Eigen +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(license) + +############################################################################## +# Export +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies(Eigen3) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_eigen/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_eigen/include/CMakeLists.txt new file mode 100644 index 0000000..1ecd018 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/include/CMakeLists.txt @@ -0,0 +1,12 @@ +############################################################################### +# Directories +############################################################################### + +if(DEFINED ECL_EIGEN_IS_INTERNAL_3_1_2) + install(DIRECTORY eigen3.1.2/Eigen DESTINATION include) + install(DIRECTORY eigen3.1.2/Eigen/unsupported DESTINATION include) +elseif(DEFINED ECL_EIGEN_IS_INTERNAL_3_2_1) + install(DIRECTORY eigen3.2.1/Eigen DESTINATION include) + # don't like this, but seems to be the only way to get unsupported found in installspace + install(DIRECTORY eigen3.2.1/Eigen/unsupported DESTINATION include) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_eigen/include/ecl/eigen.hpp.in b/ros2_ws/src/ecl_core/ecl_eigen/include/ecl/eigen.hpp.in new file mode 100644 index 0000000..5cc46a4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/include/ecl/eigen.hpp.in @@ -0,0 +1,19 @@ +/** + * @file /ecl_eigen/include/ecl/eigen.hpp + * + * @brief Defines a macro on the result of not auto-finding eigen via cmake. + * + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EIGEN_HPP_ +#define ECL_EIGEN_HPP_ + +#cmakedefine ECL_EIGEN_IS_INTERNAL_3_1_2 +#cmakedefine ECL_EIGEN_IS_INTERNAL_3_2_1 +#cmakedefine ECL_EIGEN_IS_EXTERNAL + +#endif /* ECL_EIGEN_HPP_ */ + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/license/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_eigen/license/CMakeLists.txt new file mode 100644 index 0000000..b1356a4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/license/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +set(LICENSES COPYING.LESSER) + +install(FILES ${LICENSES} DESTINATION share/licenses/eigen) + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/license/COPYING.LESSER b/ros2_ws/src/ecl_core/ecl_eigen/license/COPYING.LESSER new file mode 100644 index 0000000..fc8a5de --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/license/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/ros2_ws/src/ecl_core/ecl_eigen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_eigen/mainpage.dox new file mode 100644 index 0000000..c38b8b1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/mainpage.dox @@ -0,0 +1,24 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + +This is a package that stores the eigen header files. You can either +use it directly, or better still, interface it through ecl_linear_algebra +which provides a few extra features. + +It installs into include/eigen3.1.2/Eigen, firstly so that it keeps the installations +separate should we happen to install multiple eigens into the install space, and +secondly, it puts it in the root rather than nested inside ecl to keep it visible. + +\section Usage + +Users should only use the internal eigen if they will only access eigen from ecl +for every part of the code in their eventual binaries. We do this often for +embedded installs where the dependency list is slim, but eigen does happen to be +one of those, but lacks an installable deb or similar. + +Mixing eigen's can have compatibility issues. For example, utilising eigen 3.1.2 +from ecl would not mix with a pcl that uses a system eigen 3.0.0. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_eigen/package.xml b/ros2_ws/src/ecl_core/ecl_eigen/package.xml new file mode 100644 index 0000000..fa0e9c7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/package.xml @@ -0,0 +1,26 @@ + + + ecl_eigen + 1.2.1 + + This provides an Eigen implementation for ecl's linear algebra. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_eigen + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + eigen + + eigen + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_eigen/rosdoc.yaml b/ros2_ws/src/ecl_core/ecl_eigen/rosdoc.yaml new file mode 100644 index 0000000..584a101 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_eigen/rosdoc.yaml @@ -0,0 +1,2 @@ + - builder: doxygen + file_patterns: '*.dox' diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/.cproject b/ros2_ws/src/ecl_core/ecl_exceptions/.cproject new file mode 100644 index 0000000..075b866 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/.cproject @@ -0,0 +1,706 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + -f ${YUJIN_WORKSPACE}/build/ecl_core/${ProjName}/Makefile -j8 + + all + + true + + true + + true + + + + + + make + + -f ${YUJIN_WORKSPACE}/build/ecl_core/${ProjName}/Makefile -j8 + + clean + + true + + true + + true + + + + + + make + + -f ${YUJIN_WORKSPACE}/build/ecl_core/${ProjName}/Makefile -j8 + + examples + + true + + true + + true + + + + + + make + + benchmarks + + true + + true + + true + + + + + + make + + -f ${YUJIN_WORKSPACE}/build/ecl_core/${ProjName}/Makefile -j8 + + install + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/.project b/ros2_ws/src/ecl_core/ecl_exceptions/.project new file mode 100644 index 0000000..447fab2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/.project @@ -0,0 +1,79 @@ + + + ecl_exceptions + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_exceptions/CHANGELOG.rst new file mode 100644 index 0000000..03d9bce --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/CHANGELOG.rst @@ -0,0 +1,12 @@ +========= +Changelog +========= + +1.0.6 (2020-01-11) +------------------ +* dangling pointer on exceptions fixed, `#96 `_ + +0.61.14 (2016-06-16) +-------------------- +* expose the string message in the exception api + diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/CMakeLists.txt new file mode 100644 index 0000000..13b9796 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/CMakeLists.txt @@ -0,0 +1,50 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_exceptions) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/exceptions.dox b/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/exceptions.dox new file mode 100644 index 0000000..25364ed --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/exceptions.dox @@ -0,0 +1,243 @@ +/** +@page errorsExceptions Exceptions + +This guide focuses on the exception classes and macros made available +by the ecl to the user. + +@section Introduction + +Exceptions are usually avoided in control programs in favour of c style +error handling (return values) because the stack winding/unwinding +is too costly an overhead for control/embedded programs. However there are +some instances where it is useful. + +@subsection RAII + +Constructors cannot usually provide a means to return with detailed information +when something goes wrong - however they can with exceptions. This is especially +useful for raii (resource acquisition is initialisation) classes where a +class is completely initialised and enabled in the constructor. Since speed is +not usually of the essence in program configuration and setup (particularly in +control programs where only the control loop needs to be fast) many classes can +take advantage of exception handling in their constructors in this phase of the +program. + +@subsection Debugging + +Another is to provide a path back up the program heirarchy to ascertain where +bugs really occurred. Often a macro-function will only give you the +point of failure, which is usually in a library object somewhere - it +doesn't let you retrieve where your program caused the failure +higher up. Throwing, rethrowing and catching exceptions, in debug +mode, can do this. + +However, again, be careful of using exceptions in areas of your code which need +to be fast. The stack winding will slow your program down. + +@section types Exception Types + +@subsection Exceptions + +@link ecl::StandardException StandardException@endlink fulfills the general exception type +used by the ecl. Anywhere you wish to throw this type of exception, you +throw it by supplying the exception constructor some important information at the +point of failure. + +- LOC, the code location macro stamp defined in ecl_errors. +- One of the ErrorFlag enum values defined in ecl_errors. +- Optionally an extra string customised to provide further detail. + +@code +void f(int i) throw(StandardException) { + if ( i > 5 ) { + throw StandardException(LOC,InvalidInputError,"The maximum input is 5."); + } +} +@endcode +Typical output from this will be of the form: +@verbatim +Location : /mnt/froody/work/code/cpp/projects/ecl/modules/core/src/tests/exceptions.cpp:154 + : /mnt/froody/work/code/cpp/projects/ecl/modules/core/src/tests/exceptions.cpp:151 +Flag : There was a configuration error. +Detail : Intentionally throwing in debug mode. +@endverbatim + +If you wish to manually catch and handle them, then you can implement a handler as follows. + +@code +try { + f(6); +} catch ( StandardException &e) { + cout << e.what() << endl; + if ( e.flag() == ConfigurationError ) { + // handle the error here. + } +} +@endcode + +Note the use of the flag handler within the if statement. + +@subsection DataExceptions + +Another variant is the data exception which allows an additional data object to be bundled with +the exception. This is a templatised class. Note, if you're going to output the error +message, the data object needs to be streamable to the standard output (if not, you will get +a compile time error). + +@code + try { + throw DataException(LOC, ConfigurationError,"Throwing a data exception with an int.", 7); + } catch ( DataException &e ) { + std::cout << "Data: " << e.data() << std::endl; + std::cout << e.what() << std::endl; + } +@endcode + +@subsection posixErrorHandling Posix Error Handling Exceptions + +Usually its tedious tracking down the error number and matching it with a particular +function call's errors. There is the generic c strerror() function which can match a +generic posix errno value with a string, but this is still generic. To make this more +convenient, the PosixErrorHandler class provides a primary template for posix error +number conversions to custom StandardException types that can be thrown. As a fallback +this will use by default the strerror() function to generate a posix styled StandardException. + +The conversion is done via a static function within the specialisation, GenerateStandardException(). + +Default case example: + +@code + throw(ecl::PosixErrorHandler<>::GenerateStandardException(LOC)); +@endcode + +This automatically collects the current error value stored in the global errno variable and uses +strerror() to generate a message for the StandardException. + +An example of a specialised instance is that used for TimeStamp where the clock_gettime function +can generate posix errors: + +@code + +#include + +namespace ecl { +namespace errors { + +template<> +class PosixErrorHandler { + public: + static StandardException GenerateStandardException(const string& loc) { + + switch (errno) { + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The requested clock is not supported on this system."); + case ( EFAULT ) : return StandardException(loc, InvalidInputError, "The timespec pointer points outside the address space."); + default : return StandardException(loc, UnknownError, "Unknown posix error."); + } + } +}; +} +} +@endcode + +Use as close as possible to the posix function call: + +@code + +TimeStamp::TimeStamp() { + if ( clock_gettime(CLOCK_REALTIME,&time) ) + { + debug_throw(ecl::PosixErrorHandler::GenerateStandardException(LOC)); + } +} +@endcode + +@section rethrowingSection Rethrowing Exceptions + +You can also rethrow a StandardException, useful if you want to track the +source of the exception as it goes back up the program heirarchy. This is done +by passing the old exception to the constructor call of a new throw. + +@code +void f(int i) throw(StandardException) { + if ( i > 5 ) { + throw StandardException(LOC,InvalidInputError,"The maximum input is 5."); + } +} + +int main() { + try { + f(6); + } catch (StandardException &e) { + cout << e.what() << endl; + throw StandardException(LOC,e); // Rethrow with a new LOC + } +} +@endcode + +@section disabling Disabling Exceptions + +@subsection disableExceptions Disabling All Exceptions + +Exceptions in any of the ecl libraries can be compiled out by simply passing the +-DECL_DISABLE_EXCEPTIONS to cmake when compiling the ecl libraries (not +your program!). If building in ros you can set this variable in $ROS_ROOT/rosconfig.cmake. +Note that this variable is picked up by ecl_config where it sets a macro that is used +throughout by the ecl libraries. + +When you disable ecl exceptions, all ecl classes are designed in such a way so that +they can gracefully fall back to a lower form of error handling. + +@subsection debugSection Debug Throws + +Exceptions can also be enabled exclusively for debug mode (so long as NDEBUG is not defined) +with the @ref debug_throw macro. When NDEBUG is defined, the +throw will automatically disappear from the program code. + +@code +void f(int i) { + if ( i > 5 ) { + debug_throw( StandardException(LOC,InvalidInputError,"The maximum input is 5.") ); + } +} +@endcode + +Catching can be done with the usual try-catch blocks, but if you want to pre-process this +code away as well, you can use the debug_try and debug_catch macros. + +@code + ecl_try { + std::cout << "Try" << std::endl; + ecl_throw(ecl::StandardException(LOC,ecl::OpenError)); + } ecl_catch(ecl::StandardException &e) { + std::cout << "Catch" << std::endl; + } +@endcode + +@subsection assertSection Assert Throws + +In addition, you may use the @ref assert_throw macro +(a mechanism similar to the run_time_assert function in ecl_errors) as follows: +@code +void f(int i) { + assert_throw( i <= 5, StandardException(LOC,InvalidInputError,"The maximum input is 5.") ); +} +@endcode + +@section errata Design Notes + + The use of exceptions here doesn't exactly conform to the c++ 'ideal' for exception + handling in a library. For that you should derive from the stdexcept classes, particularly + runtime_error and logic_error and have a single class for each type of error (we've + bundled all the ecl standard errors into two classes here - Standard and Data. + However I can't seem to find a really good reason at this point in time to circumvent + the practicality of ecl_exceptions - it's just effectively simple to use for the ecl. I think + this is because the purpose of this library is to present a standard set of error types + across platforms, no need to keep making new exception classes for every new class. + package or platform implementation in the ecl. + + The only reason that might motivate a change in policy is if the ecl is used in very + heirarchical programs which require floating different exception types to different + levels depending on their type (e.g. you might want to catch an _is_busy_ error early + and recover, whilst letting a _configuration_error_ float to the top). + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/mainpage.dox new file mode 100644 index 0000000..e218605 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/doxygen/mainpage.dox @@ -0,0 +1,62 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + The embedded control libraries provide and internally make + use of a variety of error mechanisms tailored to suit + different situations. For lean and mean, there are c + style error functions and macros in ecl_errors. + At a higher level, there are template based + exceptions, these are defined in this library. + + These are further enabled via the use of macros which allow + code location (file and line #) reporting as well as + debug mode only handling. + + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit: + + @code + #include + + // The exception classes + using ecl::StandardException; + using ecl::DataException; + + // Posix Tools + using ecl::PosixErrorHandler; + + // Error flags (from ecl_errors) + using ecl::ConfigurationError; + using ecl::InvalidInputError; + //... + @endcode + + You will also need to link to -lecl_exceptions. + +@section Guides + + - @ref errorsExceptions "Exceptions" - notes on ecl exception handling. + +@section Examples + + - src/examples/exceptions.cpp : coverage style test for exceptions. + - src/examples/exception_tracer.cpp : getting a bactrace via exceptions, posix style. + +\section Benchmarks + + - ecl_core_apps/src/benchmarks/exceptions.cpp : benchmarks the latencies for exception handling. + +@section ChangeLog + + @subsection Changes + + - Feb 11 : Moved exception classes here from ecl_errors. + + @subsection Bugs + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..2a298a3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(exceptions) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions.hpp new file mode 100644 index 0000000..49575f0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions.hpp @@ -0,0 +1,33 @@ +/** + * @file /include/ecl/exceptions.hpp + * + * @brief Collects headers for ecl_exceptions. + * + * @date Feb 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_HPP_ +#define ECL_EXCEPTIONS_HPP_ + +/***************************************************************************** +** Platform Detection +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "exceptions/macros.hpp" +#include "exceptions/exception.hpp" +#include "exceptions/standard_exception.hpp" +#include "exceptions/data_exception.hpp" +#if defined(ECL_IS_POSIX) + #include "exceptions/posix_error_handler.hpp" +#endif + +#endif /* ECL_EXCEPTIONS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/CMakeLists.txt new file mode 100644 index 0000000..7cec62c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/exceptions) diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/data_exception.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/data_exception.hpp new file mode 100644 index 0000000..4eea15b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/data_exception.hpp @@ -0,0 +1,159 @@ +/** + * @file /include/ecl/exceptions/data_exception.hpp + * + * @brief Custom ecl exceptions that carry bundled data. + * + * Exceptions for try-catch handling. These exceptions + * allow bundling of some data with the exception. + * + * @date August 2008 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_DATA_EXCEPTION_HPP_ +#define ECL_EXCEPTIONS_DATA_EXCEPTION_HPP_ + +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "exception.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [DataException] +*****************************************************************************/ +/** + * @brief Extended exception class that bundles location, message and data. + * + * This exception class extends the StandardException to include an additional + * component, a single data object. Usually its a good idea to keep the data + * object small - it is copied into the exception so that it cannot be lost + * if the original object should die. + * + * The bundled data object must be streamable to standard output if this class + * is going to utilise the generic what() output. + * + * @sa Exception, StandardException, @ref errorsExceptions "Exceptions Guide". + **/ +template +class DataException : public Exception +{ + public: + DataException(const char* loc, ErrorFlag error, Data &d ); + DataException(const char* loc, ErrorFlag error, const std::string &msg, const Data &d ); + DataException(const char* loc, const DataException &e ); + + virtual ~DataException() throw() {} + + const char* what() const throw(); + + const ErrorFlag& flag() const { return error_type; } /**< @brief Flag enumerating the type of exception thrown. **/ + const Data& data() const { return error_data; } /**< @brief The bundled data object. **/ + + private: + void create_combined_message(); + ErrorFlag error_type; + Data error_data; + std::string message; + std::string combined_message; +}; + +/***************************************************************************** + * Implementation + ****************************************************************************/ +/** + * Default constructor for data exceptions. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error : enumerated exception error type. + * @param d : the data bundled with the exception. + **/ +template +DataException::DataException(const char* loc, ErrorFlag error, Data &d ) : + Exception(loc), + error_type(error), + error_data(d) +{ + create_combined_message(); +} +/** + * Constructor for data exceptions with a custom message. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error : enumerated exception error type. + * @param msg : extra detail message. + * @param d : the data bundled with the exception. + **/ +template +DataException::DataException(const char* loc, ErrorFlag error, const std::string &msg, const Data &d ) : + Exception(loc), + error_type(error), + error_data(d), + message(msg) +{ + create_combined_message(); +} +/** + * Constructor for data exceptions that enables rethrowing of an existing exception up + * the heirarchy with a new code location stamp. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param e : a caught standard exception that is to be rethrown. + **/ +template +DataException::DataException(const char* loc, const DataException &e ) : + Exception(loc), + error_type(e.flag()), + error_data(e.data()), + message(e.message) +{ + location = std::string(loc) + "\n : " + e.location; + create_combined_message(); +} + +/** + * Create the combined error message and store it. + */ +template +void DataException::create_combined_message() { + + std::ostringstream stream; + stream << "\n" << "Location : " << this->location << "\n"; + stream << "Flag : " << Error(error_type).what() << "\n"; + if ( message.size() > 0 ) { + stream << "Detail : " << message << "\n"; + } + stream << "Data : " << error_data << "\n"; + this->combined_message = stream.str(); +} + +/** + * Default exception handling output function. + * + * @return char const* : the output message. + */ +template +const char* DataException::what() const throw() { + return combined_message.c_str(); +} + +} // namespace ecl + +#endif /* ECL_DISABLE_EXCEPTIONS */ +#endif /* ECL_EXCEPTIONS_DATA_EXCEPTION_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/exception.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/exception.hpp new file mode 100644 index 0000000..379f3e1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/exception.hpp @@ -0,0 +1,76 @@ +/** + * @file /include/ecl/exceptions/exception.hpp + * + * @brief Macros and exceptions for try-catch handling within the ecl. + * + * Macros and exceptions for try-catch handling within the ecl. + * + * @date April 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_EXCEPTION_HPP_ +#define ECL_EXCEPTIONS_EXCEPTION_HPP_ + +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** General exception +*****************************************************************************/ +/** + * @brief Virtual parent class for the ecl exceptions. + * + * This is the parent class for all ecl exceptions. It cannot be instantiated + * directly - it can only be sub-classed. + * + * @sa StandardException, DataException, @ref errorsExceptions "Exceptions Guide". + **/ +class ecl_exceptions_PUBLIC Exception : public std::exception +{ + public: + /** + * Virtual method for the error message output. + */ + virtual const char * what() const throw() = 0; + virtual ~Exception() throw() {} /**< Default destructor. **/ + + protected: + /** + * Default constructor that does not configure the code location (used internally by + * the ecl when rethrowing). + */ + Exception() {} + /** + * Configures the code location - make sure you initialise this with the LOC macro. + * @param loc : use with the LOC macro, identifies the line and file of the code. + **/ + Exception(const char* loc ) : location(loc) {}; + + std::string location; +}; + +} // namespace ecl + +#endif /* ECL_DISABLE_EXCEPTIONS */ +#endif /*ECL_EXCEPTIONS_EXCEPTION_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/macros.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/macros.hpp new file mode 100644 index 0000000..1ed0240 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/macros.hpp @@ -0,0 +1,132 @@ +/** + * @file /include/ecl/exceptions/macros.hpp + * + * @brief Macros for ecl exception handling. + * + * @date March, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_MACROS_HPP_ +#define ECL_EXCEPTIONS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_exceptions_EXPORTS // we are building a shared lib/dll + #define ecl_exceptions_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_exceptions_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_exceptions_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_exceptions_PUBLIC + #define ecl_exceptions_LOCAL +#endif + +/***************************************************************************** +** Macros [ecl_throw] +*****************************************************************************/ + +#if defined(ECL_DISABLE_EXCEPTIONS) + #define ecl_throw(exception) ((void)0) + #define ecl_try if(true) + #define ecl_catch(exception) else +#else +/** + * @addtogroup Macros + * @{ +**/ +/** + * @brief Standard ecl throw exception throw. + * + * Use when throwing a function that throws a normal exception. If + * ECL_DISABLE_EXCEPTIONS is not defined, this simply inserts the required + * exception constructor otherwise it inserts nothing. + * + * @sa @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_throw(exception) throw exception; +/** + * @brief The try part of a try-catch macro matching ecl_throw calls. + * + * @sa @ref ecl_throw, @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_try try +/** + * @brief The catch part of a try-catch macro matching ecl_throw calls. + * + * @sa @ref ecl_throw, @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_catch(exception) catch(exception) +/** + * @} + **/ +#endif + +/***************************************************************************** +** Macros [ecl_assert_throw, ecl_debug_throw] +*****************************************************************************/ +/* Some bad logic here - release can still mean we use some exceptions */ +#if defined(NDEBUG) || defined(ECL_NDEBUG) || defined(ECL_DISABLE_EXCEPTIONS) + #define ecl_assert_throw(expression,exception) ((void)0) + #define ecl_debug_throw(exception) ((void)0) + #define ecl_debug_try if(true) + #define ecl_debug_catch(exception) else // TODO - this is useles, you can't do ecl_debug_catch(Exception &e) { std::cout << e.what() << std::endl; } in release mode +#else + #define ECL_HAS_EXCEPTIONS +/** + * @addtogroup Macros + * @{ +**/ +/** + * @brief Debug mode throw with a logical condition check. + * + * Does a simple logical check before throwing, only works if NDEBUG is not + * defined. + * + * @sa @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_assert_throw(expression,exception) if ( !(expression) ) { throw exception; } +/** + * @brief Debug mode exception throw. + * + * Use when throwing a debug mode only (NDEBUG is not defined) exception. This + * simply inserts the required exception constructor, otherwise it + * inserts nothing. + * + * @sa @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_debug_throw(exception) throw exception; +/** + * @brief The try part of a try-catch macro matching ecl_debug_throw/ecl_assert_throw calls. + * + * @sa @ref ecl_assert_throw, ecl_debug_throw, @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_debug_try try +/** + * @brief The catch part of a try-catch macro matching ecl_debug_throw/ecl_assert_throw calls. + * + * @sa @ref ecl_assert_throw, ecl_debug_throw, @ref errorsExceptions "Exceptions Guide". + */ + #define ecl_debug_catch(exception) catch(exception) +#endif +/** + * @} + **/ + +#endif /* ECL_EXCEPTIONS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/posix_error_handler.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/posix_error_handler.hpp new file mode 100644 index 0000000..857239d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/posix_error_handler.hpp @@ -0,0 +1,78 @@ +/** + * @file /include/ecl/exceptions/posix_error_handler.hpp + * + * @brief Exception type that handles posix errno values. + * + * Exception type that handles posix errno values and stringifies the error + * number into a human readable message. + * + * @sa @ref errorsExceptions "Exceptions Guide". + * + * @date May, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_POSIX_EXCEPTION_HPP_ +#define ECL_EXCEPTIONS_POSIX_EXCEPTION_HPP_ + +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // strerror function +#include +#include +#include "standard_exception.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [PosixErrorHandler] +*****************************************************************************/ +/** + * @brief Provides c++ mechanisms for handling posix errors. + * + * This class is a parent template for handling posix errors thrown by + * a generic base class. Currently it only serves one purpose, that is to + * redirect posix errors generated via the errno mechanism to StandardException objects. + * If you wish to customise the output of posix errors for different objects + * then simply specialise this class for the given object. See + * PosixErrorHandler for an example specialisation. + * + * @sa StandardException, @ref errorsExceptions "Exceptions Guide". + */ +template +class ecl_exceptions_PUBLIC PosixErrorHandler { +public: + /** + * This static function is the general case response for generating + * StandardException objects from a posix errno value using the c + * strerror() function. To customise the response, specialise this + * class for the required object. See + * PosixErrorHandler for an example specialisation. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ + static StandardException GenerateStandardException(const char* loc) { + return StandardException(loc, PosixError, std::string(strerror(errno))+"."); + } + virtual ~PosixErrorHandler() {} +}; + +} // namespace ecl + +#endif /* ECL_DISABLE_EXCEPTIONS */ +#endif /* ECL_EXCEPTIONS_POSIX_EXCEPTION_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/standard_exception.hpp b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/standard_exception.hpp new file mode 100644 index 0000000..c67a434 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/include/ecl/exceptions/standard_exception.hpp @@ -0,0 +1,108 @@ +/** + * @file /include/ecl/exceptions/standard_exception.hpp + * + * @brief Standard exception type, provides code location and error string. + * + * Standard exception type for try-catch handling in the ecl. It provides just + * the code location and an error message. + * + * @date April 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_EXCEPTIONS_STANDARD_EXCEPTION_HPP_ +#define ECL_EXCEPTIONS_STANDARD_EXCEPTION_HPP_ + +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "exception.hpp" +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [StandardException] +*****************************************************************************/ +/** + @brief Standard exception type, provides code location and error string. + + This exception class utilises a default set of error flags and messages + defined by the ecl. They can be coupled with the ecl exception macros + for throwing to also enable debug-only throws, assure-check throws as + well as rethrowing. + + @sa Exception, DataException, PosixErrorHandler, @ref errorsExceptions "Exceptions Guide". + **/ +class ecl_exceptions_PUBLIC StandardException : public Exception +{ + public: + /** + * @brief Default constructor for standard exceptions. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error : enumerated exception error type. + **/ + StandardException(const char* loc, ErrorFlag error ); + /** + * Constructor for standard exceptions with a custom message. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error : enumerated exception error type. + * @param msg : extra detail message. + **/ + StandardException(const char* loc, ErrorFlag error, const std::string &msg ); + /** + * Constructor for standard exceptions that enables rethrowing of an existing exception up + * the hierarchy with a new code location stamp. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param e : a caught standard exception that is to be rethrown. + **/ + StandardException(const char* loc, const StandardException &e ); + + virtual ~StandardException() throw() {} + + /** + * Default exception handling output function. + * + * @return const char* : the combined (LOC, error flag, detailed message) error string. + */ + const char* what() const throw(); + + /** + * Detailed error message associated with the exception. + * + * @return std::string : the detailed message + */ + const std::string& message() const { return detailed_message; }; + + const ErrorFlag& flag() const { return error_flag; } /**< @brief Flag enumerating the type of exception thrown. **/ + + private: + + void create_combined_message(); + + const ErrorFlag error_flag; + std::string detailed_message; + std::string combined_message; +}; + +} // namespace ecl + +#endif /* ECL_DISABLE_EXCEPTIONS */ +#endif /*ECL_EXCEPTIONS_STANDARD_EXCEPTION_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/package.xml b/ros2_ws/src/ecl_core/ecl_exceptions/package.xml new file mode 100644 index 0000000..022a511 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/package.xml @@ -0,0 +1,33 @@ + + + ecl_exceptions + 1.2.1 + + Template based exceptions - these are simple and practical + and avoid the proliferation of exception types. Although not + syntatactically ideal, it is convenient and eminently practical. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_exceptions + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + + ecl_license + ecl_config + ecl_errors + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/src/CMakeLists.txt new file mode 100644 index 0000000..ad3b151 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(lib) +add_subdirectory(examples) \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/CMakeLists.txt new file mode 100644 index 0000000..9b11df0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/CMakeLists.txt @@ -0,0 +1,17 @@ +############################################################################## +# Macros +############################################################################## + +macro(ecl_exceptions_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries(ecl_demo_${name} PUBLIC ${PROJECT_NAME} ecl_config::ecl_config) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################## +# Executables +############################################################################## + +ecl_exceptions_add_demo(exceptions) +ecl_exceptions_add_demo(exception_tracer) diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exception_tracer.cpp b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exception_tracer.cpp new file mode 100644 index 0000000..81ac8fc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exception_tracer.cpp @@ -0,0 +1,82 @@ +/** + * @file /src/examples/exception_tracer.cpp + * + * @brief Backtracing glibc style. + * + * This is an interesting exception tracer that provides functions + * and memory addresses of the backtrace where thrown. + * + * Not really useful as is, could use additional help to show + * line numbers as well. See here for a complicated example that + * does this: + * + * http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html + * + * @date March, 2011 + **/ +/***************************************************************************** +** Cross Platform +*****************************************************************************/ + +#include + +#ifndef ECL_IS_WIN32 + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // backtrace +#include +#include +#include +#include + +/***************************************************************************** +** Exceptions +*****************************************************************************/ + +/** + * @cond DO_NOT_DOXYGEN + */ +class ExceptionTracer { +public: + ExceptionTracer() { + void * array[25]; + int nSize = backtrace(array, 25); + char ** symbols = backtrace_symbols(array, nSize); + + for (int i = 0; i < nSize; i++) { + std::cout << symbols[i] << std::endl; + } + free(symbols); + } +}; + +void f() { + std::cout << "f()" << std::endl; + throw ExceptionTracer(); +} +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + std::cout << "Dude" << std::endl; + f(); + + return 0; +} +#else + +#include + +int main(int argc, char **argv) { + + std::cout << "No backtrace support in windows (that I know of yet)." << std::endl; + return 0; +} +#endif +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exceptions.cpp b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exceptions.cpp new file mode 100644 index 0000000..715e3f8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/examples/exceptions.cpp @@ -0,0 +1,303 @@ +/** + * @file /src/examples/exceptions.cpp + * + * @brief Unit test for ecl exceptions. + * + * Can't really gtest these, so this is more of a coverage test per se as + * well as an example of its usage. + * + * @sa @ref errorsExceptions "Exceptions Guide". + * + * @date April, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // fopen +#include +#include +#include "../../include/ecl/exceptions/exception.hpp" +#include "../../include/ecl/exceptions/data_exception.hpp" +#include "../../include/ecl/exceptions/macros.hpp" +#include "../../include/ecl/exceptions/standard_exception.hpp" + +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +void f(int i) +{ + if ( i > 5 ) { + ecl_debug_throw(StandardException(LOC,InvalidInputError,"Debug throw test failed, input integer exceeded.")); + } else { +// cout << "Valid integer supplied." << endl; + } +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Standard Exceptions" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + throw StandardException(LOC, NoError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, UnknownError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, OutOfRangeError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ConstructorError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, DestructorError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ConversionError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, OpenError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, CloseError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, InvalidArgError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ConfigurationError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ConnectionError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ReadError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, WriteError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, NotInitialisedError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, PermissionsError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, MemoryError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, UsageError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, RaiiError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, ArgNotSupportedError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, NotSupportedError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, BusyError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, OutOfResourcesError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + try { + throw StandardException(LOC, InterruptedError); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Standard Exceptions - Custom Message" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + throw StandardException(LOC, OutOfRangeError,"Custom detailed message."); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Standard Exceptions - Custom Message" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + try { + throw StandardException(LOC, OutOfRangeError,"Custom detailed message."); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Assert Exception Macro" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + ecl_assert_throw(2<1, StandardException(LOC, InvalidInputError,"Two is not smaller than one!")); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Debug Throw Macro" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + f(7); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Rethrowing" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + throw StandardException(LOC, ConfigurationError,"Starting spot for a rethrow."); + } catch ( StandardException &e1 ) { + try { + throw StandardException(LOC, e1); + } catch ( StandardException &e2 ) { + std::cout << e2.what() << std::endl; + } + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Try Catch" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + + std::cout << "An ecl try-catch block." << std::endl; + std::cout << std::endl; + StandardException e_original(LOC,UnknownError); + ecl_try { + std::cout << "Try" << std::endl; + ecl_throw(StandardException(LOC,e_original)); + } ecl_catch( StandardException &e ) { + std::cout << "Catch" << std::endl; + std::cout << e.what() << std::endl; + } + std::cout << "An debug try-catch block." << std::endl; + std::cout << std::endl; + ecl_debug_try { + std::cout << "Try" << std::endl; + ecl_debug_throw(StandardException(LOC,e_original)); + } ecl_debug_catch( StandardException &e ) { + std::cout << "Catch" << std::endl; + // std::cout << e.what() << std::endl; // This fails in release + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Data Exception" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + try { + throw DataException(LOC, ConfigurationError,"Throwing a data exception with an int.", 7); + } catch ( DataException &e ) { + std::cout << "Data: " << e.data() << std::endl; + std::cout << e.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} + +#else +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + std::cout << "Ecl exceptions are unavailable (ecl was compiled with ECL_DISABLE_EXCEPTIONS)." << std::endl; + + return 0; +} + +#endif /* ECL_DISABLE_EXCEPTIONS */ diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/CMakeLists.txt new file mode 100644 index 0000000..eab43e0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/CMakeLists.txt @@ -0,0 +1,37 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################## +# Targets +############################################################################## + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/standard_exception.cpp b/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/standard_exception.cpp new file mode 100644 index 0000000..af5b55f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_exceptions/src/lib/standard_exception.cpp @@ -0,0 +1,69 @@ +/** + * @file /src/lib/standard_exception.cpp + * + * @brief Implementation for standard exceptions. + * + * @date April, 2009 + **/ +/***************************************************************************** +** Disable check +*****************************************************************************/ + +#include +#include +#ifndef ECL_DISABLE_EXCEPTIONS + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/exceptions/standard_exception.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** + * Implementation [Standard Exception] + ****************************************************************************/ + +StandardException::StandardException(const char* loc, ErrorFlag error ) : + Exception(loc), + error_flag(error) +{ + create_combined_message(); +} + +StandardException::StandardException(const char* loc, ErrorFlag error, const std::string &msg ) : + Exception(loc), + error_flag(error), + detailed_message(msg) +{ + create_combined_message(); +} + +StandardException::StandardException(const char* loc, const StandardException &e ) : + Exception(), + error_flag(e.flag()), + detailed_message(e.detailed_message) +{ + location = std::string(loc) + "\n : " + e.location; + create_combined_message(); +} + +void StandardException::create_combined_message() { + this->combined_message = "\nLocation : " + this->location + "\n" + "Flag : " + Error(error_flag).what() + "\n"; + if ( this->detailed_message.size() > 0 ) { + combined_message = combined_message + "Detail : " + detailed_message + "\n"; + } +} +const char* StandardException::what() const throw() { + + return combined_message.c_str(); +} + +} // namespace ecl + +#endif /* ECL_DISABLE_EXCEPTIONS */ diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/.cproject b/ros2_ws/src/ecl_core/ecl_filesystem/.cproject new file mode 100644 index 0000000..f2582c0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/.cproject @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/.project b/ros2_ws/src/ecl_core/ecl_filesystem/.project new file mode 100644 index 0000000..3c8d0a7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/.project @@ -0,0 +1,27 @@ + + + ecl_filesystem + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_filesystem/CHANGELOG.rst new file mode 100644 index 0000000..fc461bf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/CHANGELOG.rst @@ -0,0 +1,21 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +0.61.17 (2017-02-05) +-------------------- +* bugfix implicit 'rt' dependency in catkin_package (removed) + +0.61.3 (2015-09-05) +------------------- +* fix build dirs for devel build. + +0.61.0 (2014-09-12) +------------------- +* const'ness for appropriate thread functions + +0.60.6 (2014-01-29) +------------------- +* update to catkin's CFG_EXTRAS for easy to find cmake modules. +* remove cmake debug message. +* Contributors: Daniel Stonier diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/CMakeLists.txt new file mode 100644 index 0000000..7979911 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/CMakeLists.txt @@ -0,0 +1,60 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_filesystem) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() + +# This finds the platform specific filesystem libraries and sets them in the +# variable ECL_PLATFORM_FILESYSTEM_LIBRARIES. Right now this is super simple +# (typical just 'rt' on linux), but if this gets more complicated then +# appropriate dependencies need to be listed in catkin_package's DEPENDS. +ecl_detect_filesystem() + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Do we need to export ${ECL_PLATFORM_FILESYSTEM_LIBRARIES} or does that +# automagically get covered by the exported target with target_link_libraries? + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..4742a0a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(filesystem) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem.hpp b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem.hpp new file mode 100644 index 0000000..b9d2e6e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem.hpp @@ -0,0 +1,20 @@ +/** + * @file /include/ecl/filesystem.hpp + * + * @brief Collects headers for ecl_filesystem. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FILESYSTEM_HPP_ +#define ECL_FILESYSTEM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "filesystem/realpath.hpp" + +#endif /* ECL_FILESYSTEM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/.gitignore b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/.gitignore new file mode 100644 index 0000000..a8361bc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/.gitignore @@ -0,0 +1 @@ +config.hpp diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/CMakeLists.txt new file mode 100644 index 0000000..17a25f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/CMakeLists.txt @@ -0,0 +1,19 @@ +############################################################################## +# Symbol Generation (for ecl/filesystem/config.hpp +############################################################################## + +# see ecl_detect_posix and ecl_detect_filesystem in + +if(ECL_POSIX_HAS_REALPATH) + set(ECL_PRIVATE_HAS_POSIX_REALPATH 1) +endif() +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/config.hpp) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/filesystem) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/config.hpp DESTINATION include/ecl/filesystem) diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/config.hpp.in b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/config.hpp.in new file mode 100644 index 0000000..b603f56 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/config.hpp.in @@ -0,0 +1,48 @@ +/** + * @file /include/ecl/filesystem/config.hpp + * + * @brief Pre-processed macros that define time for the platform. + * + * Cmake is used to check/verify your target platform parameters related + * to filesystem functions. At the moment this is all automated. If ever this + * needs to change (i.e. if we need to hand configure some macros as per + * ecl_config style) then we should move this to ecl_config itself. + **/ +/***************************************************************************** +** Guards +*****************************************************************************/ + +#ifndef ECL_FILESYSTEM_CONFIG_HPP_ +#define ECL_FILESYSTEM_CONFIG_HPP_ + +/***************************************************************************** +** Include +*****************************************************************************/ + +#include + +/** + * @addtogroup Macros + * @{ +**/ + +/***************************************************************************** +** Private macros +*****************************************************************************/ +/** + * @def ECL_PRIVATE_HAS_POSIX_REALPATH + * + * @brief Can utilise the posix realpath function from -lrt. +**/ +#cmakedefine ECL_PRIVATE_HAS_POSIX_REALPATH + +/***************************************************************************** +** Public macros +*****************************************************************************/ + +/** + * @} + **/ + +#endif /* ECL_FILESYSTEM_CONFIG_HPP_ */ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/errors.hpp b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/errors.hpp new file mode 100644 index 0000000..b6ac2da --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/errors.hpp @@ -0,0 +1,52 @@ +/** + * @file /ecl_time_lite/include/ecl/time_lite/errors.hpp + * + * @brief File comment + * + * File comment + * + * @date Feb 16, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_ERRORS_HPP_ +#define ECL_TIME_LITE_ERRORS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Extends the generic ecl error handler with some time specific error strings. + */ +class ecl_time_lite_PUBLIC TimeError : public Error { +public: + /** + * @brief Configures the error class with the specified error flag. + * + * @param flag : the error type. + */ + TimeError(const ErrorFlag& flag = UnknownError) : Error(flag) {} +protected: + virtual const char* outOfRangeErrorString() { return "The input time sec/nsec pair was outside of the permitted range."; } + virtual const char* argNotSupportedErrorString() { return "The clock specified is not supported on this system."; } + virtual const char* permissionsErrorString() { return "You do not have permission to set the specified clock."; } + virtual const char* memoryErrorString() { return "One of the input arguments is not in memory addressable space."; } + virtual const char* interruptedErrorString() { return "This operation was interrupted by a signal."; } +}; + +} // namespace ecl + +#endif /* ECL_TIME_LITE_ERRORS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/macros.hpp b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/macros.hpp new file mode 100644 index 0000000..3386c14 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/macros.hpp @@ -0,0 +1,38 @@ +/** + * @file /include/ecl/filesystem/macros.hpp + * + * @brief Macros for public, local export handling. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FILESYSTEM_MACROS_HPP_ +#define ECL_FILESYSTEM_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** PreProcessing +*****************************************************************************/ +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_filesystem_EXPORTS // we are building a shared lib/dll + #define ecl_filesystem_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_filesystem_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_filesystem_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_filesystem_PUBLIC + #define ecl_filesystem_LOCAL +#endif + + +#endif /* ECL_FILESYSTEM_MACROS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/realpath.hpp b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/realpath.hpp new file mode 100644 index 0000000..bbd048c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/include/ecl/filesystem/realpath.hpp @@ -0,0 +1,67 @@ +/** + * @file /include/ecl/filesystem/functions_pos.hpp + * + * @brief Simple posix implementation of ecl time functions. + * + * This implementation has its problems - most notably that you cannot get + * monotonic functionality. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FILESYSTEM_REALPATH_HPP_ +#define ECL_FILESYSTEM_REALPATH_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_PRIVATE_HAS_POSIX_REALPATH) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementations +*****************************************************************************/ +/** + * @brief Convert a path with relative markers to absolute. + * + * Expands all symbolic links and resolves references to /./, /../ and extra '/' + * characters to produce a canonicalized absolute pathname. + * + * Valid return values: + * + * - InvalidArgError, + * - ReadError, + * - InvalidObjectError, + * - InvalidArgError, + * - NotFoundError, + * - InvalidObjectError, + * + * @param path : relative or absolute path + * @return string : path with all ./ and ../ references replaced with the full path. + */ +ecl_filesystem_PUBLIC ecl::Error realpath(const std::string& path, std::string& absolute_path); + + +} // namespace ecl + +#endif /* ECL_PRIVATE_HAS_POSIX_REALPATH */ +#endif /* ECL_FILESYSTEM_REALPATH_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/package.xml b/ros2_ws/src/ecl_core/ecl_filesystem/package.xml new file mode 100644 index 0000000..8ed1652 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/package.xml @@ -0,0 +1,36 @@ + + + ecl_filesystem + 1.2.1 + + Cross platform filesystem utilities (until c++11 makes its way in). + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_filesystem + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + + ecl_license + ecl_build + ecl_config + ecl_errors + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/src/CMakeLists.txt new file mode 100644 index 0000000..45123f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/CMakeLists.txt new file mode 100644 index 0000000..5fb136d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/CMakeLists.txt @@ -0,0 +1,42 @@ +############################################################################### +# SOURCES +############################################################################### + +# Note, macro magic stops us compiling objects for the wrong implementations below +SET(SOURCES + realpath.cpp +) +############################################################################### +# Install +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + PUBLIC + $ + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors + ${ECL_PLATFORM_FILESYSTEM_LIBRARIES} +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/realpath.cpp b/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/realpath.cpp new file mode 100644 index 0000000..4bc7922 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/src/lib/realpath.cpp @@ -0,0 +1,70 @@ +/** + * @file /src/lib/realpath.cpp + * + * @brief Realpath implementations. + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#if defined(ECL_PRIVATE_HAS_POSIX_REALPATH) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include // limits.h +#include // stdlib.h +#include +#include +#include "../../include/ecl/filesystem/realpath.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [realpath] +*****************************************************************************/ + +ecl_filesystem_PUBLIC ecl::Error realpath(const std::string& path, std::string& absolute_path) { + int path_max; + // see the man page for realpath for details + #ifdef PATH_MAX + path_max = PATH_MAX; /* PATH_MAX from limits.h, but not always defined */ + #else + path_max = pathconf(path, _PC_PATH_MAX); + if (path_max <= 0) { path_max = 4096; } /* Not guaranteed to give you results */ + #endif + + char *buffer = new char[path_max]; + char *result = ::realpath(path.c_str(), buffer); + absolute_path = buffer; + if ( result != NULL ) { + absolute_path = buffer; + } else { + switch(errno) { + case(EACCES) : { return Error(PermissionsError); } // Read or search permission was denied for a component of the path prefix. + case(EINVAL) : { return Error(InvalidArgError); } // path is NULL + case(EIO) : { return Error(ReadError); } // An I/O error occurred while reading from the filesystem. + case(ELOOP) : { return Error(InvalidObjectError); } // too many symbolic links were encountered in translating the pathname + case(ENAMETOOLONG) : { return Error(InvalidArgError); } // A component of a pathname exceeded NAME_MAX characters, or an entire pathname exceeded PATH_MAX characters. + case(ENOENT) : { return Error(NotFoundError); } // The named file does not exist + case(ENOTDIR) : { return Error(InvalidObjectError); } // A component of the path prefix is not a directory. + default : { return Error(UnknownError); } + } + } + delete[] buffer; + return Error(NoError); +} + +} // namespace ecl + +#endif /* ECL_PRIVATE_HAS_POSIX_REALPATH */ + diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_filesystem/src/test/CMakeLists.txt new file mode 100644 index 0000000..aaa71b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/src/test/CMakeLists.txt @@ -0,0 +1,17 @@ +############################################################################### +# Test Macro +############################################################################### + +macro(ecl_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_add_gtest(realpath) diff --git a/ros2_ws/src/ecl_core/ecl_filesystem/src/test/realpath.cpp b/ros2_ws/src/ecl_core/ecl_filesystem/src/test/realpath.cpp new file mode 100644 index 0000000..3a7fbbc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_filesystem/src/test/realpath.cpp @@ -0,0 +1,42 @@ +/** + * @file /src/test/realpath.cpp + * + * @brief Unit Test for the realpath function. + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_PRIVATE_HAS_POSIX_REALPATH) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +//#include +#include +#include +#include "../../include/ecl/filesystem/realpath.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(FilesystemTests,realpath) { + std::string abs_path; + std::string rel_path = "./experiment.dslam"; + + ecl::realpath(rel_path, abs_path); + // TODO : right now, we have no idea of where this will run. Once we have + // a `pwd` like function later, insert it here to derive the test properly. + //EXPECT_EQ(std::string("Foo"), abs_path); + std::cout << "Absolute path: " << abs_path << std::endl; + SUCCEED(); +} + +#endif /* ECL_PRIVATE_HAS_POSIX_REALPATH */ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/.cproject b/ros2_ws/src/ecl_core/ecl_formatters/.cproject new file mode 100644 index 0000000..64422cc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/.cproject @@ -0,0 +1,338 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + true + true + true + + + make + + test + true + true + true + + + make + + all + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/.project b/ros2_ws/src/ecl_core/ecl_formatters/.project new file mode 100644 index 0000000..d9dfd46 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/.project @@ -0,0 +1,78 @@ + + + ecl_formatters + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_formatters/CHANGELOG.rst new file mode 100644 index 0000000..9e76e82 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/CHANGELOG.rst @@ -0,0 +1,12 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_formatters +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.60.8 (2014-02-10) +------------------- + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_formatters/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/CMakeLists.txt new file mode 100644 index 0000000..69e14b9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/CMakeLists.txt @@ -0,0 +1,52 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_formatters) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_converters REQUIRED) +find_package(ecl_exceptions REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_converters + ecl_exceptions +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_formatters/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_formatters/doxygen/mainpage.dox new file mode 100644 index 0000000..ba072be --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/doxygen/mainpage.dox @@ -0,0 +1,233 @@ +/** +\mainpage +\htmlinclude manifest.html + +@section packageSummary Package Summary + +The formatters here simply format various input types to a specified +text format. If you wish to just do fast type to text conversion +without formatting, use the converters supplied in ecl_utilities. + +@section History + + Type to text formatting is usually bundled with both streaming and + device manipulation. Although this makes it very simple to do the + most basic of type formatting, it also has the unfortunate consequence + in that the formatter types (printf, sprintf, iostreams) are very + heavyweight and subsequently slow. Especially for a simple task, they + bring a sledge hammer when all that is needed is a gentle push. + + What the formatters attempt to do is to split the functionality + of formatting from the concepts of device manipulation, + streaming. This ensures that any simple task is not overdone with a + heavyweight object (really important for logging) and it greatly enhances + the efficiency and speed. The classes here also bring in type safety, + something which is not guaranteed by either printf or sprintf. + + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The formatter template family + using ecl::Format; + + // Common formatter parameters + using ecl::NoAlign; + using ecl::LeftAlign; + using ecl::CentreAlign; + using ecl::RightAlign; + + // Integral formatter parameters + using ecl::Bin; + using ecl::Dec; + using ecl::Hex; + + // Float formatter parameters + using ecl::Fixed; + using ecl::Sci; + + @endcode + + You will also need to link to -lecl_formatters. + +\section usage Usage + + @subsection Instantiation + + Formatters are functors - functions with state. You instantiate a formatter + type and then make use of it as if it were a function call. + + @code + Format format(); // Default format initialisation + Format format(8,RightAlign,Hex); // Custom format initialisation + @endcode + + @subsection FormatChange Changing the Format Parameters + + The format parameters can be changed singly with appropriately named + setters, or collectively via:: a bundled operator () call. Sometimes + common combinations are also provided with a convenient setter via the operator (). + + @code + format.base(Hex) + format(8,RightAlign,Dec) + @endcode + + Changing the format parameters in this way will set the default formatting + for any input values given to the formatter in the future. + + @subsection FormattersStreaming Streaming + + The formatters are primarily intended to be used with streams. For convenience + they have been designed to be used with any stream that implemenents the + << operator. Subsequently they are useful with either TextStreams (ECL-IO) or + the usual c++ streams. When used in conjunction with TextStreams they provide + a very fast streaming interface. + + @subsection PermanentFormatting Permanent Formatting + + To format with the parameters stored in the formatter, you simply + provide the formatter with the input value. Note that the formatter will + only accept a value of the type specified in the formatter's template + argument. + + @code + ostream << format(i) << " " << format(9); + @endcode + + For convenience, you can also change the format parameter on the fly (this is + recorded permanently). + @code + ostream << format.base(Hex)(i) << " " << format(10,LeftAlign,Dec)(9); + @endcode + + @subsection TemporaryFormatting Temporary Formatting + + Occasionally you will only need to change the format for one instance. + To effect a temporary change in this way, supply the input value + along with the specified formatting options. + + @code + ostream << format(i,6,CentreAlign,Hex); + @endcode + + @subsection FormatterFunctionality Functionality + + Always check the formatter's interface to see what setters are + available to the type you wish to format. Although there are common + formatting parameters, they are few and these will usually vary from type + to type. + + @subsection FormattersSpeedSection Performance + + Some results from tests on a 64 bit gentoo installed on a dual core II computer + while formatting both integer and float types indicate that when used in conjunction + with TextStream, the formatters are 7-30x faster than their printf and + iostream equivalents (which perform roughly as well as each other). + Run the test program for evaluation on your machine. + +@section healthHazards Health Hazards + + There are some awkward aspects of streaming that make it difficult for the formatters to + function perfectly. Without going into the details, there are various issues with + the unspecifiedness of function arguments that mean its impossible to format several + objects on the same line differently, and expect the result to come back in the + correct order. I haven't currently got a solution for this, so there are two + options: + - 1) Leave the formatters as they are and ensure that only one + formatter is used on each line (abort/throw if this occurs), or + - 2) Push the formatters back into TextStream. + + The second option is no good - it just turns TextStream into a heavyweight iostream. + A priority for us is fast logging, so we must keep TextStream lightweight and since + 1) is merely a coding style issue, that's easy to handle so long as we are aware of + it. + + @subsection okUsage Permitted Usage + + @code + ostream << "[" << format(q.x()); + ostream << ", " << format(q.y()); + ostream << ", " << format(q.z()) << "]"; + @endcode + + @subsection bannedUsage Not permitted Usage + + @code + ostream << "[" << format(q.x()) << ", " << format(q.y()) ostream << ", " << format(q.z()) << "]"; + @endcode + + In debug mode, formatters use an exception throwing assert to check that multiple formatters aren't + used in the one line when streaming. + + @section FormattingTypes Types + + Formatters cover all the basic fundamental types (char, float, double, int...). They + also cover a few special types, including arrays - refer to the documentation for ecl_containers + for more information. + + @section FormattersWriting Writing Your Own Formatters + + Formatters must implement + - Formatting setters + - Input value operator + - Temporary formatting operators + - Streaming friend function + + @code + class MatrixFormatter { + public: + MatrixFormatter& precision(int p); // Setter + MatrixFormatter& operator()(Matrix M); // Input Operator + MatrixFormatter& operator(int p, int w ... ); // Combination setter + MatrixFormatter& operator(Matrix M, int p, int w ...); //Temporary formatting operator + template friend OutputStream& operator << (OutputStream& ostream, MatrixFormatter& formatter); + } + @endcode + Note that the setters and operators must return the formatter so that the friend function can implement the formatting. + + For the Format class to automagically find this formatter, you can implement one of two methods. + If you have access to the class's internals, simply typedef it as "Formatter" inside the class, otherwise + simply specialise the Format<> class for your type and inherit the formatter. + + @code + // Method one, if you have access to the classes internals + class Matrix { + public: + typedef MatrixFormatter Formatter; + }; + // Method two + template <> + class Format : public MatrixFormatter {}; + @endcode + + +@section ConverterList Current List of Formatters + + Each standard formatter is a template specialisation of the form Format where the available input types are: + + - integral types (char, short, int, long, long long and their unsigned equivalents) + - float types (float, double) + - string + - fixed size arrays/stencils + + Note, as with any string based object, avoid it if you need speed with your streaming. + +\section unitTests Unit Tests + + - src/examples/formatters.cpp : not a google unit test, but does coverage. + +\section ChangeLog + + - Sep 10 : Moved container arrays to the ecl_containers class. + - Mar 10 : Char stencils can now use the same formatter as their underlying array. + - May 09 : Added width formatting capabilities to float containers. + - May 09 : Added formatters for fixed size char, float and double arrays. + - May 09 : Fixed speed issues by converting to an underlying snprintf implementation (temp. hack). + - May 09 : Added formatters for fundamental number types and strings. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_formatters/doxygen/namespaces.dox new file mode 100644 index 0000000..0819135 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/doxygen/namespaces.dox @@ -0,0 +1,15 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::interfaces + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..668f1a1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(formatters) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters.hpp new file mode 100644 index 0000000..29ae793 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/formatters.hpp + * + * @brief Text stream formatting classes. + * + * Defines formatters that can alter individual objects before sending them + * to a text stream. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_HPP_ +#define ECL_FORMATTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "formatters/common.hpp" +#include "formatters/number.hpp" +#include "formatters/floats.hpp" +#include "formatters/strings.hpp" + +#endif /*ECL_FORMATTERS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/CMakeLists.txt new file mode 100644 index 0000000..1e71edb --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/formatters) + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/common.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/common.hpp new file mode 100644 index 0000000..34e2456 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/common.hpp @@ -0,0 +1,103 @@ +/** + * @file /include/ecl/formatters/common.hpp + * + * @brief Common formatting definitions. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_COMMON_HPP_ +#define ECL_FORMATTERS_COMMON_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Format Tags +*****************************************************************************/ +/** + * @brief Alignment tags for text formatting. + * + * Common alignment format tag for the formatters. + **/ +enum Alignment +{ + NoAlign, /**< @brief No alignment used. **/ + LeftAlign, /**< @brief Align to the left. **/ + RightAlign, /**< @brief Align to the right. **/ + CentreAlign, /**< @brief Align in the centre. **/ +}; + +/***************************************************************************** +** Default precision widths +*****************************************************************************/ +/* + * These must match the default format precisions for each fundamental type. + */ +/** + * @brief Precision width trait for fundamental types. + * + * Numerical metafunction used by the default insertion + * operator to establish the width of a cell when a matrix is sent to + * an output stream. This value will generally store the space required + * by integers for decimal precision (i.e. none). + */ +template struct PrecisionWidth { + public: + static const int value = 0; +}; + +/** + * @brief Precision width trait for floats. + * + * Numerical metafunction used by the default insertion operator to + * establish the width of a cell when a matrix is sent to an output + * stream. This value determines the number of cells required + * for the default level of decimal precision (four decimal places). + */ +template <> +struct PrecisionWidth { + public: + static const int value = 4; +}; + +/** + * @brief Precision width trait for doubles. + * + * Numerical meta-function used by the default insertion operator to + * establish the width of a cell when a matrix is sent to an output + * stream. This value determines the number of cells required + * for the default level of decimal precision (four decimal places). + */ +template <> +struct PrecisionWidth { + public: + static const int value = 4; +}; + +/***************************************************************************** +* Format Classes +*****************************************************************************/ +/** + * @brief Primary template for all formatter classes. + * + * Most formatters specialise from this primary template, however if no + * specialisation exists, this will look up the class to be formatted + * interface for a formatter type to use (T::Formatter). There are many + * basic type specialisations in the formatters namespace. + * + * @sa ecl::formatters. + * + **/ +template +class Format : public T::Formatter {}; + +} // namespace ecl + +#endif /*ECL_FORMATTERS_COMMON_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/floats.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/floats.hpp new file mode 100644 index 0000000..ace8dbe --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/floats.hpp @@ -0,0 +1,538 @@ +/** + * @file /include/ecl/formatters/floats.hpp + * + * @brief Interface for the float (float,double) formatter. + * + * @todo add code for the scientific formatting of a float. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_FLOATS_HPP_ +#define ECL_FORMATTERS_FLOATS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // snprintf +#include // strlen +#include "common.hpp" +#include + +#if _MSC_VER +#define snprintf _snprintf +#endif + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Format Tags +*****************************************************************************/ +/** + * @brief Base format tags for the float formatters. + * + * Base format tags for text formatting of floats. + **/ +enum FloatBase +{ + Fixed, /**< @brief Fixed formatting for floats (i.e. normal decimal representation). **/ + Sci, /**< @brief Scientific formatting for floats (i.e. exponential representation). **/ +}; + +namespace interfaces { + +/***************************************************************************** +** FormatFloat +*****************************************************************************/ + +/** + * @brief Formatter for float types. + * + * Default formatter for float types. For convenience, use the individual + * Format classes that inherit this one instead. + **/ +template +class FormatFloat { +public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Default constructor. Initialises the format tags for width, precision, alignment and base. + * @param w : width (default - no width constraints) + * @param p : the number of decimal places of precision (default - 4) + * @param a : the textual alignment (default - no alignment constraints) + * @param b : the base format for the floating point representation (default - fixed) + **/ + FormatFloat(const int w = -1, const unsigned int p = 4, const ecl::Alignment a = NoAlign, const ecl::FloatBase b = Fixed) : + prm_width(w), + prm_precision(p), + prm_alignment(a), + prm_base(b), + width_(&prm_width), + precision_(&prm_precision), + alignment_(&prm_alignment), + base_(&prm_base), + ready_to_format(false) {} + + virtual ~FormatFloat() {} + + /****************************************** + ** Set Format Parameters + *******************************************/ + /** + * @brief Sets the precision format parameter. + * + * Sets the precision format parameter. + * + * @param p : the number of decimal places of precision. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& precision(const unsigned int p) { *precision_ = p; return *this; } + /** + * @brief Sets the width format parameter. + * + * Sets the width format parameter. + * + * @param w : the width to use for the inserted float (-1 is no width constraint). + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& width(const int w); + /** + * @brief Sets the alignment format parameter. + * + * Sets the alignment format parameter. + * + * @param a : the textual alignment. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& align(const ecl::Alignment a); + /** + * @brief Sets the base notation to use. + * + * Sets the base notation to use (fixed or scientific). + * + * @param b : the base format for the floating point representation. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& base(const ecl::FloatBase b); + + /****************************************** + ** Get Format Parameters + *******************************************/ + /** + * @brief Returns the current precision setting. + * @return int : the precision value. + */ + int precision() { return *precision_; } + + /** + * @brief Returns the current precision setting. + * + * @return int : the width value (-1 for no constraint). + */ + int width() { return *width_; } + + /****************************************** + * Set Format Combinations + ******************************************/ + /** + * Convenient stream format parameter setter. This one permanently configures the width and precision as specified. + * @param p : the number of decimal places of precision. + * @param w : the total width of the text output. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& operator()(unsigned int p, const int w); + /** + * Convenient stream format parameter setter. This one permanently configures all parameters. + * @param p : the number of decimal places of precision. + * @param w : the total width of the text output. + * @param align : the aligning property for the output text. + * @param b : the base representation used for the output. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& operator()(const unsigned int p, const int w, const ecl::Alignment align, const ecl::FloatBase b); + + /****************************************** + ** Format a value + *******************************************/ + /** + * Convenient stream formatter. This function directly formats + * the specified input value with the stored settings. + * @code + * Format format; + * cout << format(3,4)(3.5215233) << endl; + * @endcode + * @param n : the input value to be formatted. + * @return FormatFloat& : this formatter readied for use with a stream. + **/ + FormatFloat& operator() (const Number n); + + /****************************************** + ** Format for streaming + *******************************************/ + /** + * Convenient stream formatter. This member directly formats the specified input value with the supplied/temporary parameters. + * @param n : the input value to be formatted. + * @param p : the number of decimal places of precision. + * @param w : the total width of the text output. + **/ + FormatFloat& operator() (const Number n, const unsigned int p, const int w); + /** + * Convenient stream formatter. This member directly formats the specified input value with the supplied/temporary parameters. + * @param n : the input value to be formatted. + * @param p : the number of decimal places of precision. + * @param w : the total width of the text output. + * @param align : the aligning property for the output text. + * @param b : the base representation used for the output. + **/ + FormatFloat& operator() (const Number n, const unsigned int p, const int w, const ecl::Alignment align, const ecl::FloatBase b); + + /****************************************** + ** Insert the formatter into a stream + *******************************************/ + /** + * Friend function which allows a stream to act on the formatter to produce + * the formatted result. This works on normal c++ streams + * as well as TextStreams. + * @param ostream : the stream. + * @param formatter : the formatter with prespecified format parameters and input value. + * @return OutputStream& : return the stream that was utilised. + **/ +template +friend OutputStream& operator << (OutputStream& ostream, FormatFloat& formatter); + +protected: + /****************************************** + ** Parameters + *******************************************/ + int prm_width,tmp_width; + int prm_precision,tmp_precision; + ecl::Alignment prm_alignment,tmp_alignment{}; + ecl::FloatBase prm_base,tmp_base; + int *width_, *precision_; + ecl::Alignment *alignment_; + ecl::FloatBase *base_; + bool ready_to_format; + Number value_; + + /****************************************** + ** Padding + *******************************************/ + template void pad(int n, OutputStream &ostream) const; + template void prePad(int n, OutputStream &ostream) const; + template void postPad(int n, OutputStream &ostream) const; + + /****************************************** + ** Formatter Functions + *******************************************/ + template void formatFixed(OutputStream &ostream) const; + template void formatSci(OutputStream &ostream) const; +}; + +/***************************************************************************** +* FormatFloat Implementation [single parameter configuration] +*****************************************************************************/ +/** + * Sets the base format. For floating point values, this can be fixed, exponential or scientific. + * @param b : the base representation used for the output. + * @sa FloatBase + **/ +template +FormatFloat& FormatFloat::base(const ecl::FloatBase b) +{ + *base_ = b; + return *this; +} +/** + * Sets the width format parameter. Setting this to -1 will turn off width formatting constraints. + * @param w : the total width of the text output. + **/ +template +FormatFloat& FormatFloat::width(const int w) +{ + *width_ = w; + if ( ( *width_ > 0 ) && ( *alignment_ == NoAlign ) ) + { + *alignment_ = RightAlign; + } + return *this; +} + +/** + * Sets the alignment format parameter. This aligns the text output in the text window which has a width specified by the width parameter. + * @param a : the aligning property for the output text. + * @sa Alignment + **/ +template +FormatFloat& FormatFloat::align(const ecl::Alignment a) +{ + *alignment_ = a; + if ( *alignment_ == NoAlign ) + { + *width_ = 0; + } + return *this; +} + +/***************************************************************************** +* FormatFloat Implementation [format combination configuration] +*****************************************************************************/ + +template +FormatFloat& FormatFloat::operator () (const unsigned int p, const int w) +{ + width(w); + precision(p); + return *this; +} + +template +FormatFloat& FormatFloat::operator () (const unsigned int p, const int w, const ecl::Alignment a, const ecl::FloatBase b) +{ + width(w); + precision(p); + align(a); + base(b); + return *this; +} + +/***************************************************************************** +* FormatFloat Implementation [value] +*****************************************************************************/ +template +FormatFloat& FormatFloat::operator()(const Number n) +{ + value_ = n; + ready_to_format = true; + return *this; +} +/***************************************************************************** +* FormatFloat Implementation [temporary formatting] +*****************************************************************************/ +template +FormatFloat& FormatFloat::operator() (const Number n, unsigned int p, const int w) +{ + width_ = &tmp_width; + width(w); + + precision_ = &tmp_precision; + precision(p); + + alignment_ = &tmp_alignment; + align(prm_alignment); + + base_ = &tmp_base; + base(prm_base); + + value_ = n; + ready_to_format = true; + return *this; +} + +template +FormatFloat& FormatFloat::operator() (const Number n, const unsigned int p, const int w, const ecl::Alignment a, const ecl::FloatBase b) +{ + width_ = &tmp_width; + width(w); + + precision_ = &tmp_precision; + precision(p); + + alignment_ = &tmp_alignment; + align(a); + + base_ = &tmp_base; + base(b); + + value_ = n; + ready_to_format = true; + return *this; +} + + +/***************************************************************************** +* FormatFloat Implementation [internal formatting] +*****************************************************************************/ +template + template +void FormatFloat::formatFixed(OutputStream &ostream) const +{ + static char format_specifier[6] = "%.xff"; + if ( *precision_ < 10 ) { + format_specifier[2] = '0'+*precision_; + format_specifier[3] = 'f'; + format_specifier[4] = '\0'; + } else if ( *precision_ < 20 ) { + format_specifier[2] = '1'; + format_specifier[3] = '0'+(*precision_ - 10); + format_specifier[4] = 'f'; + } else { + format_specifier[2] = '2'; + format_specifier[3] = '0'; + format_specifier[4] = 'f'; + } + static const int buffer_size = 30; + static char buffer[buffer_size]; + + snprintf(buffer, buffer_size, format_specifier, value_); + + /****************************************** + ** Streaming out + *******************************************/ + int length = strlen(buffer); + prePad(*width_ - length,ostream); + ostream << buffer; + postPad(*width_ - length,ostream); +} + +template + template +void FormatFloat::formatSci(OutputStream &ostream) const +{ + ostream << "Scientific format is not yet supported." << "\n"; + ostream.flush(); +} + +template + template +void FormatFloat::prePad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( *alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { break; } + case ( RightAlign ) : { pad(n,ostream); break; } + case ( CentreAlign ) : { pad(n/2+ n%2,ostream); break; } // Add the remainder + default : break; + } +} + +template + template +void FormatFloat::postPad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( *alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { pad(n,ostream); break; } + case ( RightAlign ) : { break; } + case ( CentreAlign ) : { pad(n/2,ostream); break; } // Do not add the remainder + default : break; + } +} + +template + template +void FormatFloat::pad(int n, OutputStream &ostream) const +{ + for (int i = n; i > 0; --i ) + { + ostream << ' '; + } +} + +/***************************************************************************** +* FormatFloat Implementation [streaming] +*****************************************************************************/ +template +OutputStream& operator << (OutputStream &ostream, FormatFloat& formatter ) +{ + bool ready = formatter.ready_to_format; + + ecl_assert_throw(ready, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + if ( ready ) + { + switch(*(formatter.base_) ) + { + case(Fixed) : { + formatter.formatFixed(ostream); + break; + } + case(Sci) : { + formatter.formatSci(ostream); + break; + } + } + + // Switch pointers back to prms if not already there. + if ( formatter.width_ != &(formatter.prm_width) ) { + formatter.width_ = &(formatter.prm_width); + formatter.precision_ = &(formatter.prm_precision); + formatter.alignment_ = &(formatter.prm_alignment); + formatter.base_ = &(formatter.prm_base); + } + formatter.ready_to_format = false; + } + return ostream; +} + +} // namespace interfaces + +/***************************************************************************** +* Format Classes +*****************************************************************************/ +/** + * @brief Formatter for float types. + * + * It is a specialisation of the Format template family. Its entire functionality + * is inherited from FormatFloat (this class simply provides a convenient handle in the + * Format family). + **/ +template <> +class Format : public interfaces::FormatFloat +{ + public: + /** + * Default constructor. Initialises the format tags for width, precision, alignment and base. + * @param w : width (default - no width constraints) + * @param p : the number of decimal places of precision (default - 4) + * @param a : the textual alignment (default - no alignment constraints) + * @param b : the base format for the floating point representation (default - fixed) + **/ + Format(int w = -1, int p = 4, Alignment a = NoAlign, FloatBase b = Fixed) : + interfaces::FormatFloat(w, p, a, b) {} + + virtual ~Format() {} +}; +/** + * @brief Formatter for double types. + * + * It is a specialisation of the Format template family. Its entire functionality + * is inherited from FormatFloat (this class simply provides a convenient handle in the + * Format family). + **/ +template <> +class Format : public interfaces::FormatFloat +{ + public: + /** + * Default constructor. Initialises the format tags for width, precision, alignment and base. + * @param w : width (default - no width constraints) + * @param p : the number of decimal places of precision (default - 4) + * @param a : the textual alignment (default - no alignment constraints) + * @param b : the base format for the floating point representation (default - fixed) + **/ + Format(int w = -1, int p = 4, Alignment a = NoAlign, FloatBase b = Fixed) : + interfaces::FormatFloat(w, p, a, b) { + } + + virtual ~Format() {} +}; + +} // namespace ecl + +#endif /*ECL_FORMATTERS_FLOATS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/macros.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/macros.hpp new file mode 100644 index 0000000..223974d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/formatters/macros.hpp + * + * @brief Macros for ecl formatters. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_MACROS_HPP_ +#define ECL_FORMATTERS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_formatters_EXPORTS // we are building a shared lib/dll + #define ecl_formatters_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_formatters_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_formatters_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_formatters_PUBLIC + #define ecl_formatters_LOCAL +#endif + +#endif /* ECL_FORMATTERS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/number.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/number.hpp new file mode 100644 index 0000000..d486a06 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/number.hpp @@ -0,0 +1,557 @@ +/** + * @file /include/ecl/formatters/number.hpp + * + * @brief Integral type formatter. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_NUMBER_HPP_ +#define ECL_FORMATTERS_NUMBER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "common.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Format Tags +*****************************************************************************/ +/** + * @brief Base format tags for the integral formatters. + * + * Format tags for text formatting of integral numbers. + **/ +enum IntegralBase +{ + Bin, /**< @brief Binary representation for integral types. **/ + Hex, /**< @brief Hex representation for integral types. **/ + Dec, /**< @brief Decimal (i.e. normal) representation for integral types. **/ +}; + +namespace interfaces { + +/***************************************************************************** +** FormatNumber Interface [Integral types] +*****************************************************************************/ + +/** + * @brief Formatter for integral types. + * + * Default formatter for integral types. For convenience, use the individual + * Format classes that inherit this one instead. + **/ +template < typename Number > +class FormatNumber { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Default constructor. Initialises the format tags for width, alignment and base. + * @param w : width (default - no width constraints) + * @param a : the textual alignment (default - no alignment constraints) + * @param b : the base format for the integral representation (default - decimal) + **/ + FormatNumber(int w = -1, ecl::Alignment a = NoAlign, ecl::IntegralBase b = Dec) : prm_width(w),prm_alignment(a),prm_base(b),width_(&prm_width),alignment_(&prm_alignment),base_(&prm_base),ready_to_format(false) {} + + virtual ~FormatNumber() {} + + /****************************************** + ** Set + *******************************************/ + /** + * Sets the base format. For integral types, this can be binary, hexadecimal or decimal. + * @param b : the base representation used for the output. + * @sa IntegralBase + **/ + FormatNumber& base(ecl::IntegralBase b); + /** + * Sets the width format parameter. Setting this to -1 will turn off width formatting constraints. + * @param w : the total width of the text output. + **/ + FormatNumber& width(int w); + /** + * Sets the alignment format parameter. This aligns the text output in the text window which has a width specified by the width parameter. + * @param a : the aligning property for the output text. + * @sa ecl::formatters::Alignment + **/ + FormatNumber& align(ecl::Alignment a); + + /****************************************** + * Set Format Combinations + ******************************************/ + /** + * Convenient stream format parameter setter. This one permanently configures the width alignment and base as specified. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + * @return FormatNumber& : this formatter readied for use by a stream. + **/ + FormatNumber& operator ()(int w, ecl::Alignment a, ecl::IntegralBase b); + + /****************************************** + ** Format a value + *******************************************/ + /** + * Convenient stream formatter. This function directly formats the specified + * input value with the stored settings. + * @param n : the input value to be formatted. + * @return FormatNumber& : this formatter readied for use by a stream. + **/ + FormatNumber& operator() (Number n); + + /****************************************** + ** Common format usages + *******************************************/ + /** + * Convenient stream formatter. This member directly formats the specified + * input value with the supplied/temporary parameters. + * @param n : the input value to be formatted. + * @param w : the total width of the text output. + * @param b : the base representation used for the output. + * @return FormatNumber& : this formatter readied for use by a stream. + **/ + FormatNumber& operator() (Number n, int w, ecl::IntegralBase b); + /** + * Convenient stream formatter. This member directly formats the specified + * input value with the supplied/temporary parameters. + * @param n : the input value to be formatted. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + * @return FormatNumber& : this formatter readied for use by a stream. + **/ + FormatNumber& operator() (Number n, int w, ecl::Alignment a, ecl::IntegralBase b); + + /****************************************** + ** Insert the formatter into a stream + *******************************************/ + /** + * Friend function which allows a stream to act on the formatter to produce + * the formatted result. This works on normal c++ streams + * as well as TextStreams. + * @param ostream : the stream. + * @param formatter : the formatter with prespecified format parameters and input value. + * @return OutputStream& : return the stream that was utilised. + * + * @exception StandardException : throws if the formatter is used multiply in one stream operation [debug mode only]. + **/ + template friend OutputStream& operator << (OutputStream& ostream, FormatNumber& formatter); + + protected: + /****************************************** + ** Paramaters + *******************************************/ + int prm_width, tmp_width; + ecl::Alignment prm_alignment, tmp_alignment; + ecl::IntegralBase prm_base, tmp_base; + int *width_; + ecl::Alignment *alignment_; IntegralBase *base_; + bool ready_to_format; + Number value_; + + /****************************************** + ** Padding + *******************************************/ + template void pad(int n, OutputStream &ostream) const; + template void prePad(int n, OutputStream &ostream) const; + template void postPad(int n, OutputStream &ostream) const; + + /****************************************** + ** Formatter Functions + *******************************************/ + template void formatBin(OutputStream &ostream) const; + template void formatHex(OutputStream &ostream) const; + template void formatDec(OutputStream &ostream) const; + +}; // FormatNumber + +/***************************************************************************** +* FormatNumber Implementation [configuration] +*****************************************************************************/ +template +FormatNumber& FormatNumber::base(ecl::IntegralBase b) +{ + *base_ = b; + return *this; +} + +template +FormatNumber& FormatNumber::width(int w) +{ + *width_ = w; + if ( ( *width_ > 0 ) && ( *alignment_ == NoAlign ) ) { + *alignment_ = RightAlign; + } + return *this; +} + +template +FormatNumber& FormatNumber::align(ecl::Alignment a) +{ + *alignment_ = a; + if ( *alignment_ == NoAlign ) + { + *width_ = 0; + } + return *this; +} +template +FormatNumber& FormatNumber::operator () (int w, ecl::Alignment a, ecl::IntegralBase b) +{ + base(b); + width(w); + align(a); + return *this; +} + +/***************************************************************************** +* FormatNumber Implementation [internal formatting] +*****************************************************************************/ +template + template +void FormatNumber::formatBin(OutputStream &ostream) const +{ + int size = 8*sizeof(Number); + prePad(*width_ - (size + 2),ostream); + ostream << "0b"; + for (int i = size - 1; i>=0; i--) + { + ostream << "01"[((value_ >> i) & 1)]; + } + postPad(*width_ - (size + 2),ostream); +} + +template + template +void FormatNumber::formatHex(OutputStream &ostream) const +{ + static const char hex_string[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; + + int size = 2*sizeof(Number); + prePad(*width_ - (size + 2),ostream); + ostream << "0x"; + for (int i = size - 1; i>=0; i--) + { +// ostream << "0123456789abcdef"[((value_ >> i*4) & 0xF)]; + ostream << hex_string[((value_ >> i*4) & 0xF)]; // Dont have to recreate this every time + } + postPad(*width_ - (size + 2),ostream); +} + +template + template +void FormatNumber::formatDec(OutputStream &ostream) const +{ + static ecl::Converter convert; + char *s = convert(value_); + int size = strlen(s); + prePad(*width_ - size,ostream); + ostream << s; + postPad(*width_ - size,ostream); +} + +template + template +void FormatNumber::prePad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( *alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { break; } + case ( RightAlign ) : { pad(n,ostream); break; } + case ( CentreAlign ) : { pad(n/2+ n%2,ostream); break; } // Add the remainder + default : break; + } +} + +template + template +void FormatNumber::postPad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( *alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { pad(n,ostream); break; } + case ( RightAlign ) : { break; } + case ( CentreAlign ) : { pad(n/2,ostream); break; } // Do not add the remainder + default : break; + } +} + +template + template +void FormatNumber::pad(int n, OutputStream &ostream) const +{ + for (int i = n; i > 0; --i ) + { + ostream << ' '; + } +} +/***************************************************************************** +* FormatNumber Implementation [value] +*****************************************************************************/ +/** + * Insert an input value to be formatted when passed to a stream. + **/ +template +FormatNumber& FormatNumber::operator()(Number n) +{ + value_ = n; + ready_to_format = true; + return *this; +} + +/***************************************************************************** +* FormatNumber Implementation [temporary formatting] +*****************************************************************************/ + +/** + * Temporarily configure the formatter with a width, base combination along with a value to be formatted. + **/ +template +FormatNumber& FormatNumber::operator() (Number n, int w, ecl::IntegralBase b) +{ + width_ = &tmp_width; + alignment_ = &tmp_alignment; + base_ = &tmp_base; + base(b); + width(w); + value_ = n; + ready_to_format = true; + return *this; +} +/** + * Temporarily configure the formatter with a complete parameter set along with a value to be formatted. + **/ +template +FormatNumber& FormatNumber::operator() (Number n, int w, ecl::Alignment a, ecl::IntegralBase b) +{ + width_ = &tmp_width; + alignment_ = &tmp_alignment; + base_ = &tmp_base; + base(b); + width(w); + align(a); + value_ = n; + ready_to_format = true; + return *this; +} + + +/***************************************************************************** +* FormatNumber Implementation [streaming] +*****************************************************************************/ +template +OutputStream& operator << (OutputStream &ostream, FormatNumber& formatter ) +{ + bool ready = formatter.ready_to_format; + + ecl_assert_throw(ready, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + if ( ready ) + { + switch(*(formatter.base_) ) + { + case(Bin) : { + formatter.formatBin(ostream); + break; + } + case(Hex) : { + formatter.formatHex(ostream); + break; + } + case(Dec) : { + formatter.formatDec(ostream); + break; + } + } + if ( formatter.width_ != &(formatter.prm_width) ) { + formatter.width_ = &(formatter.prm_width); + formatter.alignment_ = &(formatter.prm_alignment); + formatter.base_ = &(formatter.prm_base); + } + formatter.ready_to_format = false; + } + return ostream; +} + +} // namespace interfaces + +/***************************************************************************** +* Format Classes +*****************************************************************************/ +/** + * @brief Formatter for short types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; +/** + * @brief Formatter for int types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; +/** + * @brief Formatter for long types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; + +/** + * @brief Formatter for char types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; + +/** + * @brief Formatter for signed char types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; + +/** + * @brief Formatter for unsigned short types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; + +/** + * @brief Formatter for unsigned int types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; +/** + * @brief Formatter for unsigned long types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + /** + * Default constructor. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @param b : the base representation used for the output. + */ + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} + virtual ~Format() {} +}; +/** + * @brief Formatter for unsigned char types. It is a specialisation of the Format + * class. + **/ +template <> +class Format : public interfaces::FormatNumber +{ + public: + Format(int w = -1, Alignment a = NoAlign, IntegralBase b = Dec) : interfaces::FormatNumber(w, a, b) {} /**< Default constructor. */ + virtual ~Format() {} +}; + +} // namespace ecl + +#endif /*ECL_FORMATTERS_NUMBER_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/strings.hpp b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/strings.hpp new file mode 100644 index 0000000..c4832c4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/include/ecl/formatters/strings.hpp @@ -0,0 +1,243 @@ +/** + * @file /include/ecl/formatters/strings.hpp + * + * @brief String type formatter. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_FORMATTERS_STRINGS_HPP_ +#define ECL_FORMATTERS_STRINGS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "common.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Format Interface [String types] +*****************************************************************************/ + +/** + * @brief Formatter for string types. + * + * Default formatter for string types. + * This is pretty slow since we're using strings, but its convenient when + * speed is not an issue. + **/ +template <> +class ecl_formatters_PUBLIC Format { + public: + /****************************************** + ** C&D's + *******************************************/ + /** + * Default constructor. Initialises the format tags for width, alignment and base. + * @param w : width (default - no width constraints) + * @param a : the textual alignment (default - no alignment constraints) + **/ + Format(int w = -1, Alignment a = NoAlign) : width_(w),alignment_(a) {} + virtual ~Format() {} + + /****************************************** + ** Set + *******************************************/ + /** + * Sets the width format parameter. Setting this to -1 will turn off width formatting constraints. + * @param w : the total width of the text output. + **/ + Format& width(int w) { width_ = w; return *this; } + /** + * Sets the alignment format parameter. This aligns the text output in the text window which has a width specified by the width parameter. + * @param a : the aligning property for the output text. + * @sa Alignment + **/ + Format& align(Alignment a) { alignment_ = a; return *this; } + + /****************************************** + * Set Format Combinations + ******************************************/ + /** + * Convenient stream format parameter setter. This one permanently configures the width and alignment as specfied. + * @param w : the total width of the text output. + * @param a : the aligning property for the output text. + * @return Format& : this formatter (for use with streams). + **/ + Format& operator ()(int w, Alignment a); + + /****************************************** + ** Format a value + *******************************************/ + /** + * Insert an input value to be formatted when passed to a stream. + * @param input_string : the string to be formatted. + * @return Format : formatting object to be passed back to the stream. + **/ + Format& operator() (const std::string &input_string); + + /****************************************** + ** Common format usages + *******************************************/ + /** + * Temporarily configure the formatter with a width, base combination along with a value to be formatted. + * @param input_string : the string to be formatted. + * @param w : the width to be used. + * @return Format : formatting object to be passed back to the stream. + **/ + Format& operator() (const std::string &input_string, int w); + /** + * Temporarily configure the formatter with a complete parameter set along with a value to be formatted. + * @param input_string : the string to be formatted. + * @param w : the width to be used. + * @param a : the alignment to be used. + * @return Format : formatting object to be passed back to the stream. + * + **/ + Format& operator() (const std::string &input_string, int w, Alignment a); + + /****************************************** + ** Insert the formatter into a stream + *******************************************/ + /** + * Insertion operator for formatters. It takes a customised formatter and + * inserts its current context into the stream. If two formatters are used + * in succession, it will throw an error (c++ cannot handle two in a single + * line of streaming). This works on normal c++ streams + * as well as TextStreams. + * @param ostream : the stream to insert the formatted object into. + * @param formatter : the format context. + * @return OutputStream : a handle to the resultant stream. + * + * @exception StandardException : throws if the formatter is used multiply in one stream operation [debug mode only]. + **/ + template friend OutputStream& operator << (OutputStream& ostream, Format& formatter); + + private: + /****************************************** + ** Parameters + *******************************************/ + int width_; + Alignment alignment_; + bool ready_to_format; + std::string s; + + /****************************************** + ** Padding + *******************************************/ + /** + * Internally used to pad the output with spaces when requested. + * @param n : the number of spaces to pad. + * @param ostream : the streaming operator the formatter is conencted to. + **/ + template void pad(int n, OutputStream &ostream) const; + /** + * Prepad the output with spaces when requested. + * @param n : the number of spaces to pad. + * @param ostream : the streaming operator the formatter is conencted to. + **/ + template void prePad(int n, OutputStream &ostream) const; + /** + * Postpad the output with spaces when requested. + * @param n : the number of spaces to pad. + * @param ostream : the streaming operator the formatter is conencted to. + **/ + template void postPad(int n, OutputStream &ostream) const; + + /****************************************** + ** Formatter Functions + *******************************************/ + /** + * Internal function that does the actual formatting of a format object into a stream. + * @param ostream : the stream to be inserted into. + **/ + template void format(OutputStream &ostream) const; +}; + +/***************************************************************************** +** Implementation [Format][Templates] +*****************************************************************************/ + +template +void Format::format(OutputStream &ostream) const +{ + int size = s.size(); + + prePad(width_ - (size),ostream); // previously had (size+2) here...why? + ostream << s; + postPad(width_ - (size),ostream); +} + +template +void Format::prePad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { break; } + case ( RightAlign ) : { pad(n,ostream); break; } + case ( CentreAlign ) : { pad(n/2+ n%2,ostream); break; } // Add the remainder + default : break; + } +} +template +void Format::postPad(int n, OutputStream &ostream) const +{ + if ( n <= 0 ) { return; } + switch ( alignment_ ) + { + case ( NoAlign ) : { break; } + case ( LeftAlign ) : { pad(n,ostream); break; } + case ( RightAlign ) : { break; } + case ( CentreAlign ) : { pad(n/2,ostream); break; } // Do not add the remainder + default : break; + } +} +template +void Format::pad(int n, OutputStream &ostream) const +{ + for (int i = n; i > 0; --i ) + { + ostream << ' '; + } +} + +/***************************************************************************** +* Implementation [streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, Format& formatter ) +{ + bool ready = formatter.ready_to_format; + + ecl_assert_throw(ready, StandardException(LOC,UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + if ( ready ) { + formatter.format(ostream); + formatter.ready_to_format = false; + } + + return ostream; +} + +} // namespace ecl + +#endif /*ECL_FORMATTERS_STRINGS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_formatters/package.xml b/ros2_ws/src/ecl_core/ecl_formatters/package.xml new file mode 100644 index 0000000..df553aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/package.xml @@ -0,0 +1,34 @@ + + + ecl_formatters + 1.2.1 + + The formatters here simply format various input types to a specified + text format. They can be used with most streaming types (including both + ecl and stl streams). + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_formatters + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_exceptions + ecl_converters + + ecl_license + ecl_config + ecl_exceptions + ecl_converters + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/src/CMakeLists.txt new file mode 100644 index 0000000..87ba9b8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/src/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(lib) +add_subdirectory(examples) +#add_subdirectory(test) diff --git a/ros2_ws/src/ecl_core/ecl_formatters/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/src/examples/CMakeLists.txt new file mode 100644 index 0000000..c86406f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/src/examples/CMakeLists.txt @@ -0,0 +1,20 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_formatters_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries( + ecl_demo_${name} + PUBLIC + ${PROJECT_NAME} + ) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_formatters_add_demo(formatters) diff --git a/ros2_ws/src/ecl_core/ecl_formatters/src/examples/formatters.cpp b/ros2_ws/src/ecl_core/ecl_formatters/src/examples/formatters.cpp new file mode 100644 index 0000000..f0cef66 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/src/examples/formatters.cpp @@ -0,0 +1,163 @@ +/** + * @file /src/test/formatters.cpp + * + * @brief Test program for the formatters. + * + * Can't really feasibly do a unit test on the formatters, so this is + * more just a coverage test. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/formatters/common.hpp" +#include "../../include/ecl/formatters/floats.hpp" +#include "../../include/ecl/formatters/number.hpp" +#include "../../include/ecl/formatters/strings.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::Format; +using ecl::Dec; +using ecl::Fixed; +using ecl::Hex; +using ecl::CentreAlign; +using ecl::LeftAlign; +using ecl::NoAlign; +using ecl::RightAlign; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + + unsigned char c = 69; + Format format(8,RightAlign,Hex); // Initialisation + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Temporary Formatting [Number]" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "NoAlign : " << format(c,8,NoAlign,Hex) << std::endl; + std::cout << "LeftAlign : " << format(c,8,LeftAlign,Hex) << std::endl; + std::cout << "CentreAlign: " << format(c,8,CentreAlign,Hex) << std::endl; + std::cout << "RightAlign : " << format(c,8,RightAlign,Hex) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Temporary Formatting [Number]" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "NoAlign : " << format(c,8,NoAlign,Hex) << std::endl; + std::cout << "LeftAlign : " << format(c,8,LeftAlign,Hex) << std::endl; + std::cout << "CentreAlign: " << format(c,8,CentreAlign,Hex) << std::endl; + std::cout << "RightAlign : " << format(c,8,RightAlign,Hex) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Permanent Formatting [Number]" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "NoAlign : " << format(8,NoAlign,Hex)(c) << std::endl; + std::cout << "LeftAlign : " << format(8,LeftAlign,Hex)(c) << std::endl; + std::cout << "CentreAlign: " << format(8,CentreAlign,Hex)(c) << std::endl; + std::cout << "RightAlign : " << format(8,RightAlign,Hex)(c) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Single Parameter Formatting [Number]" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Width : " << format.width(14)(c) << std::endl; + std::cout << "Align : " << format.align(CentreAlign)(c) << std::endl; + std::cout << "Base : " << format.base(Dec)(c) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Integral Types" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "char : " << Format(8,RightAlign,Dec)('c') << std::endl; + std::cout << "short : " << Format(8,RightAlign,Dec)(123) << std::endl; + std::cout << "unsigned short: " << Format(8,RightAlign,Dec)(123) << std::endl; + std::cout << "int : " << Format(8,RightAlign,Dec)(-111123) << std::endl; + std::cout << "unsigned int : " << Format(8,RightAlign,Dec)(111123) << std::endl; + std::cout << "long : " << Format(8,RightAlign,Dec)(-1111123) << std::endl; + std::cout << "unsigned long : " << Format(8,RightAlign,Dec)(1111123) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " String Formats" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Format sformat(10,RightAlign); + std::cout << "Strings: " << sformat(string("Dude")) << std::endl; + std::cout << "Strings: " << sformat(string("Dudette")) << std::endl; + std::cout << "Strings: " << sformat(string("Dudonimous")) << std::endl; + std::cout << "CString: " << sformat("Dude") << std::endl; + std::cout << "TmpFrmt: " << sformat("Dude",10,CentreAlign) << std::endl; + std::cout << "PrmFrmt: " << sformat(10,CentreAlign)("Dude") << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Float Formats" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Format fformat; + float f = -12235.135; + fformat.base(Fixed); + fformat.width(15); + fformat.precision(3); + fformat.align(LeftAlign); + fformat.align(CentreAlign); + fformat.align(RightAlign); + fformat(2,15,RightAlign,Fixed); + fformat(2,15); + std::cout << "TmpFrmt: " << fformat(f,2,15,CentreAlign,Fixed) << std::endl; + std::cout << "TmpFrmt: " << fformat(f,2,15) << std::endl; + std::cout << "Format : " << fformat(f) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Double Formats" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Format dformat; + double d = 134.2352; + dformat.base(Fixed); // Format setters + dformat.width(15); + dformat.precision(3); + dformat.align(LeftAlign); + dformat.align(CentreAlign); + dformat.align(RightAlign); + dformat(2,15,RightAlign,Fixed); // Combo format operators + dformat(4,15); + std::cout << "TmpFrmt: " << dformat(d,2,15,CentreAlign,Fixed) << std::endl; + std::cout << "TmpFrmt: " << dformat(d,3,15) << std::endl; + std::cout << "Format : " << dformat(d) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_formatters/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_formatters/src/lib/CMakeLists.txt new file mode 100644 index 0000000..a3a06ae --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/src/lib/CMakeLists.txt @@ -0,0 +1,39 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_converters::ecl_converters + ecl_exceptions::ecl_exceptions +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + diff --git a/ros2_ws/src/ecl_core/ecl_formatters/src/lib/strings.cpp b/ros2_ws/src/ecl_core/ecl_formatters/src/lib/strings.cpp new file mode 100644 index 0000000..fe0a763 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_formatters/src/lib/strings.cpp @@ -0,0 +1,67 @@ +/** + * @file /src/lib/strings.cpp + * + * @brief Implementation for the string formatter. + * + * @date May, 2009. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/formatters/strings.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; + +/***************************************************************************** +** Implementation [Format] +*****************************************************************************/ + +Format& Format::operator () (int w, Alignment a) +{ + width(w); + align(a); + return *this; +} + +Format& Format::operator()(const std::string &input_string) +{ + s = input_string; + ready_to_format = true; + return *this; +} + +/***************************************************************************** +* Implementation [temporary formatting] +*****************************************************************************/ +Format& Format::operator() (const std::string &input_string, int w) +{ + width(w); + s = input_string; + ready_to_format = true; + return *this; +} +Format& Format::operator() (const std::string &input_string, int w, Alignment a) +{ + width(w); + align(a); + s = input_string; + ready_to_format = true; + return *this; +} + +} // namespace ecl + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/.cproject b/ros2_ws/src/ecl_core/ecl_geometry/.cproject new file mode 100644 index 0000000..30e11d3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/.cproject @@ -0,0 +1,676 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + all + + true + + true + + true + + + + + + make + + + + test + + true + + true + + true + + + + + + make + + + + clean + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/.project b/ros2_ws/src/ecl_core/ecl_geometry/.project new file mode 100644 index 0000000..d0e886a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/.project @@ -0,0 +1,78 @@ + + + ecl_geometry + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_geometry/CHANGELOG.rst new file mode 100644 index 0000000..d328d17 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/CHANGELOG.rst @@ -0,0 +1,21 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_geometry +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +1.1.1 (2020-09-10 +----------------- +* new pose2d methods and convenience class + +0.61.15 (2016-11-09) +-------------------- +* pose -> legacy pose +* new pose (function only) library started, should eliminate the need for most type conversions + +0.61.7 (2016-01-09) +------------------- +* avoid cubic spline calculations when incoming data has only one point + +0.61.1 (2015-07-22) +------------------- +* linear segments and shortest path to these + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/CMakeLists.txt new file mode 100644 index 0000000..94dc834 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/CMakeLists.txt @@ -0,0 +1,65 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_geometry) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_containers REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_linear_algebra REQUIRED) +find_package(ecl_math REQUIRED) +find_package(ecl_mpl REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_containers + ecl_exceptions + ecl_formatters + ecl_linear_algebra + ecl_math + ecl_mpl + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/angles.dox b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/angles.dox new file mode 100644 index 0000000..bebfb46 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/angles.dox @@ -0,0 +1,59 @@ +/** + @page anglesGuide Angles + + @section Introduction + + Simplifies the calls to angle-related functions such as angle wrapping, degree-radian + conversions, rotation matrix representations. + + @section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that uses + geometry functions or classes. + + @code + #include + + using ecl::Angle; + using ecl::wrap_angle; + @endcode + + You will also need to link to -lecl_geometry. + + @section Usage + + @subsection Functions + + For those who prefer to use function based libraries, the ecl::wrap_angle function can + be used to operate on simple float types. + + @code + double angle = wrap_angle(3.33); + @endcode + + For conversions: + + @code + double rads = radians_to_degrees(1.44); + double degrees = degrees_to_radians(rads); + @endcode + + @subsection Classes + + The angle class is a convenience class that automates storage and angle wrapping for + you. It uses by default, radians (which any good engineer/mathematician should default to!). + Take this into consideration if using it where speed is of the essence. That is, + don't use Angle and then do all your calculations in degrees - there will be alot of copying! + + @code + Angle a(3.33); // automatically wraps on -pi:pi + double degrees = a.degrees(); + Angle b = a + 3.24; // again, will automatically wrap the answer. + Angle::RotationMatrix matrix = a.rotationMatrix(); // currently using a 2d eigen matrix. + @endcode + +@section unitTests Unit Tests + + - src/test/angles.cpp + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/mainpage.dox new file mode 100644 index 0000000..a487cf3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/mainpage.dox @@ -0,0 +1,97 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This group includes various structures and tools used in geometry + as well as various supporting classes and utilities. + +@section compSection External Components + + There are quite a few useful tools also in eigen's geometry module. You can get access to these + via the ecl_linear_algebra module. + + - angle-axis pairs + - quaternions + - rotation matrices + - transforms + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Angles + using ecl::Angle; + using ecl::wrap_angle; + using ecl::degrees_to_radians; + using ecl::radians_to_degrees; + // Other Objects + using ecl::CartesianPoint; + using ecl::PascalsTriangle; + // Functions that act on functions + using ecl::Minimum; + using ecl::Maximum; + // Functions + using ecl::Polynomial; // Also has some typedefs, LinearFunction, CubicPolynomial, QuadraticPoly... + using ecl::TensionFunction; + // Splines + using ecl::SmoothLinearSpline; + using ecl::CubicSpline; + using ecl::TensionSpline; + // Transforms + using ecl::Pose2D; + @endcode + + You will also need to link to -lecl_geometry. + +@section groupSection Usage + + Refer to the class api/guide for each component. + + - @ref anglesGuide "Angles" - c++ style wrapper for angles (radians) and unit conversions (deg<->rad). + - @ref ecl::CartesianPoint "Cartesian Points" - generic and specialised representations for cartesian points. + - @ref ecl::Pose2D "Pose2D" - extends eigen's geometry transforms with a 2d specialised version. + - @ref polynomialsGeometry "Polynomials" - polynomial functions and two-point interpolations. + - @ref splinesGeometry "Splines" - generating various splines and interpolating over a set of data. + + +\section unitTests Unit Tests + + - src/test/angles.cpp + - src/test/cartesian_points.cpp + - src/test/cubic_splines.cpp + - src/test/polynomials.cpp + - src/test/smooth_linear_splines.cpp + - src/test/tension_function.cpp + - src/test/tension_splines.cpp + - src/test/pose2d.cpp + +@section ChangeLog + + - Sep 10 : ecl::Pose2D transform established, very much eigen style. + - Jul 10 : ecl::Angle is finalised with float/double versions and a functional api to assist. + - Jul 09 : ecl::BluePrintFactory is a blueprint factory for linear functions. + - Jul 09 : ecl::blueprints::LinearInterpolation is a blueprint for linear interpolation between end points. + - Jul 09 : ecl::SmoothLinearSpline is a a smoothed, linearly blend spline (with quintics). + - May 09 : ecl::blueprints::QuinticInterpolation is a blueprint for quintic interpolation between end points. + - May 09 : ecl::BluePrintFactory is a blueprint factory for quintic polynomials. + - May 09 : ecl::blueprints::CubicSecondDerivativeInterpolation is a blueprint for acceleration derived interpolations between two end points. + - May 09 : ecl::blueprints::CubicDerivativeInterpolation is a blueprint for velocity derived interpolations between two end points. + - May 09 : ecl::BluePrintFactory is a blueprint factory for cubic polynomials. + - May 09 : ecl::Polynomial is a templatised class representing polynomials of arbitrary degree. + - May 09 : A simple templatisation for @ref ecl::PascalsTriangle "pascals triangle" of arbitrary degree. + - May 09 : ecl::blueprints::C2TensionSpline is a c2 continuous tension spline interpolation. + - May 09 : ecl::TensionSpline is a representation for a tension spline. + - May 09 : ecl::TensionFunction is a representation for a tension function. + - May 09 : ecl::blueprints::C2CubicSpline is a special case of the C2CubicSpline, the natural cubic spline. + - May 09 : ecl::blueprints::C2CubicSpline is a blueprint for C2 continous splines over a set of data. + - May 09 : ecl::blueprints::DerivativeHeuristicCubicSpline uses an automated velocity based heuristic to generate a cubic spline on a data set. + - May 09 : ecl::BluePrintFactory is a blueprint factory for cubic splines. + - May 09 : ecl::CubicSpline is a typedef'd representation for a cubic spline. + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/namespaces.dox new file mode 100644 index 0000000..99a0dce --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/namespaces.dox @@ -0,0 +1,18 @@ + /** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::blueprints + * + * @brief Blueprints and factories classes used to generate blueprints. + * + * The blueprints are used to generate lightweight classes that store the rules to + * instantiate or configure classes in this package. These are used automatically with the + * factories to develop constructors and assignments with a convenient notation so you + * should never need to directly use these classes. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/natural_cubic_spline.png b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/natural_cubic_spline.png new file mode 100644 index 0000000..28a28a5 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/natural_cubic_spline.png differ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/polynomials.dox b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/polynomials.dox new file mode 100644 index 0000000..d8775be --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/polynomials.dox @@ -0,0 +1,154 @@ +/** + @page polynomialsGeometry Polynomials + + @section Introduction + + This group includes various structures and tools for polynomials. + + @section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that uses + geometry functions or classes. + + @code + #include + + // The classes + using ecl::Maximum; + using ecl::Minimum; + using ecl::PascalsTriangle; + using ecl::Polynomial; + // Typedefs to Polynomial<> + using ecl::LinearFunction; + using ecl::QuadraticPolynomial; + using ecl::CubicPolynomial; + using ecl::QuinticPolynomial; + @endcode + + You will also need to link to -lecl_geometry. + + @section Usage + + @subsection Polynomial + + Polynomials are embedded in the usual c++ wrapper. Coefficient storage is + based on the array class in ecl_containers, so + comma initialisation can be used to configure the polynomial appropriately. + + @code + // Comma Initialisation + Polynomial<5> p; + p.coefficients() = 1,2,3,4,5,6; + cout << p << endl; // 1.00 + 2.00x + 3.00x^2 + 4.00x^3 + 5.00x^4 + 6.00x^5 + @endcode + + There is also a method for shifting the polynomial on the horizontal axis + (later, if there is a need a vertical shift will be added). + + @subsection Typedefs + + Rather than specifying the degree of the polynomial with a template argument, + a few more convenient typedefs are available: + + @code + typedef Polynomial<1> LinearFunction; + typedef Polynomial<2> QuadraticPolynomial; + typedef Polynomial<3> CubicPolynomial; + typedef Polynomial<5> QuinticPolynomial; + @endcode + + @subsection BluePrints + + There are also some blueprints for generating polynomials that interpolate + between two end points. These can be accessed via static methods that are inherited + by the polynomial's class. For example: + + @code + LinearFunction linear = LinearFunction::Interpolation(0.0,0.0,1.0,2.0); // x_i, y_i, x_f, y_f + LinearFunction linear = LinearFunction::PointSlopeForm(1.0,2.0,2.0); // x_f, y_f, slope + CubicPolynomial cubic; + cubic = CubicPolynomial::DerivativeInterpolation(2.0,0.0,0.0,3.0,1.0,0.0); // x_i, y_i, y'_i, x_f, y_f, y'_f + cubic = CubicPolynomial::SecondDerivativeInterpolation(2.0,0.0,0.0,3.0,1.0,0.0); // x_i, y_i, y''_i, x_f, y_f, y''_f + QuinticPolynomial quintic = QuinticPolynomial::Interpolation(0.0,0.0,0.0,0.0,1.0,2.0,1.0,0.0); // x_i, y_i, y'_i, y''_i, x_f, y_f, y'_f, y''_f + @endcode + + - ecl::CubicPolynomial::DerivativeInterpolation + + @subsection ptSection Pascal's Triangle + + Pascal's triangle is used to calculate the coefficients for polynomial + expansion. The class here accepts a template parameter N and calculates + all the coefficients up to order N (i.e. for polynomial expansion up to + (x+y)^N). + + You can stream the output directly if you just need to view + them or you can use an stl style iterator to traverse the rows diagonally. + Simply call the usual begin function with an integer argument representing + the diagonal you're interested in. The first iterator will traverse + from the top of the triangle to the bottom right. As you increase the index + the diagonals shift down and to the left. + + There may be a future addition to allow horizontal row representations. Also note, + specialised (low N) versions of these exist that directly set coefficients so as to + avoid expensive calculations. + + @code + PascalsTriangle<5> pascals_triangle; + cout << pascals_triangle << endl; + cout << "Row iteration [2]: "; + PascalsTriangle<5>::const_iterator row_iter; + for (row_iter = pascals_triangle.begin(2); row_iter != pascals_triangle.end(2); ++row_iter) { + cout << *row_iter << " "; + } + cout << endl; + @endcode + +@section geometryFunctions Polynomial Functions + + There also exist various functions that operate on polynomials. These currently include: + + - ecl::Roots + - ecl::Intersection + - ecl::Maximum + - ecl::Minimum + - ecl::Division + - ecl::Roots + - ecl::Division + - ecl::Roots + - ecl::Maximum + - ecl::Minimum + + They can also be called from the function classes themselves if it is preferred, e.g. + + @code + double maximum = ecl::Maximum()(0.0, 0.2, p); + @endcode + + OR + + @code + double maximum = ecl::CubicPolynomial::Maximum(0.0, 0.2, p); + @endcode + + +@section units Unit Tests + + - src/test/polynomials.cpp + +@section ChangeLog + + - Dec 11 : ecl::Division also cubics, long division (by synthetic method). + - Dec 11 : ecl::Root root solvers (also quadratic and cubic). + - Dec 11 : ecl::FunctionMath is a math loader for function classes. + - Dec 11 : ecl::Intersection operator added. + - Dec 11 : ecl::BluePrintFactory added a slope-point form blueprint. + - Jul 09 : ecl::BluePrintFactory is a blueprint factory for linear functions. + - Jul 09 : ecl::blueprints::LinearInterpolation is a blueprint for linear interpolation between end points. + - May 09 : ecl::blueprints::QuinticInterpolation is a blueprint for quintic interpolation between end points. + - May 09 : ecl::BluePrintFactory is a blueprint factory for quintic polynomials. + - May 09 : ecl::blueprints::CubicSecondDerivativeInterpolation is a blueprint for acceleration derived interpolations between two end points. + - May 09 : ecl::blueprints::CubicDerivativeInterpolation is a blueprint for velocity derived interpolations between two end points. + - May 09 : ecl::BluePrintFactory is a blueprint factory for cubic polynomials. + - May 09 : ecl::Polynomial is a templatised class representing polynomials of arbitrary degree. + - May 09 : A simple templatisation for @ref ecl::PascalsTriangle "pascals triangle" of arbitrary degree. +**/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/smooth_linear_splines.png b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/smooth_linear_splines.png new file mode 100644 index 0000000..b141c63 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/smooth_linear_splines.png differ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/splines.dox b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/splines.dox new file mode 100644 index 0000000..84e7f91 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/splines.dox @@ -0,0 +1,154 @@ +/** + @page splinesGeometry Splines + + @section Introduction + + Classes representing continuously connected functions (splines) and some + interpolation algorithms. + + @section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that uses + geometry functions or classes. + + @code + #include + + // The classes + using ecl::CubicSpline; + using ecl::SmoothLinearSpline; + using ecl::TensionSpline; + @endcode + + You will also need to link to -lecl_geometry. + + @section cubicSplineUsage Usage - CubicSpline + + @subsection CubicSpline + + The @ref ecl::CubicSpline "CubicSpline" has a relatively simple c++ interface. + + - Generation of splines via blueprint algorithms. + - Access for any x, the spline value, its derivative or its second derivative. + - A streamed (algebraic) representation. + + @subsection BluePrints + + The blueprints generate a cubic spline over a data set. Depending on the input constraints, + the spline is generated rather differently. + These can be accessed via static methods in the blueprint factory + (ecl::BluePrintFactory< CubicSpline >) inherited by the CubicSpline class. + For example: + + @code + CubicSpline cubic; + cubic = CubicSpline::Natural(x_set, y_set); + cubic = CubicSpline::ContinuousDerivatives(x_set, y_set, ydot_0, ydot_f); + cubic = CubicSpline::DerivativeHeuristic(x_set, y_set, ydot_0, ydot_f); + @endcode + + @subsection Access + + Access allows you to calculate the value of the spline at any point on its domain: + @code + std::cout << "Value : " << cubic(3.2) << std::endl; + std::cout << "1st Derivative: " << cubic.derivative(3.2) << std::endl; + std::cout << "2nd Derivative: " << cubic.dderivative(3.2) << std::endl; + @endcode + + @subsection Algebraic + + Streaming will provide an algebraic list of the cubic polynomials constituting the spline. + + @code + std::cout << cubic << std::endl; + // Typical output + // 1.00 + 2.31x + 3.00x^2 + 1.23x^3 + // 0.00 + 1.42x + 5.20x^2 + 1.06x^3 + @endcode + + @subsection cubicPic Illustration + + @image html natural_cubic_spline.png + + @section smoothLinearSplineUsage Usage - SmoothLinearSpline + + @subsection SmoothLinearSpline + + The @ref ecl::SmoothLinearSpline "SmoothLinearSpline" simply linearly connects waypoints + and adds a quintic polynomial curve to smooth the corners between each linear section. The + shape of these corners is parameterised by a maximum curvature (acceleration) parameter. + + @subsection smoothConstruction Construction + + Simply pass suitable x and y data sets along with a maximum curvature constraint parameter + to the spline's constructor. Be sure to catch an exception if the construction should fail (this + will occur if the maximum curvature constraint cannot be met). + + @code + double max_curvature = 5.0; + SmoothLinearSpline spline(x_set, y_set, max_curvature); + @endcode + + @subsection smoothAccess Access & Algebraic Forms + + Access and streaming is similar to that for the cubic spline. + + @subsection linearPic Illustration + + @image html smooth_linear_splines.png + + @section tensionSplineUsage Usage - TensionSpline + + @subsection TensionSpline + + The @ref ecl::TensionSpline "TensionSpline" represents a mathematically parameterised + spline that portrays the whole family of splines from linearly connected segments through + to cubic polynomials. To do this it uses the tension function. When connecting tension + functions across a series of waypoints, the tension parameter provides this extra flexibility + in controlling the shape of the spline. + + - Low tension : it behaves exactly like the cubic spline. + - High tension : it behaves like a spline composed of linear segments. + + Note that its primary advantages are that it is still C2 continuous and it is very easy to modify + the resulting behaviour through tweaking of a single parameter. + + @subsection BluePrints + + There is currently only one blueprint (though variations are not difficult to create). It + is very similar to the natural cubic spline (assumes zero boundary conditions for the + second derivatives), the only difference being the addition of the tension parameter. + + @code + TensionSpline spline = TensionSpline::Natural(tension, x_set, y_set); + @endcode + + @subsection tensionAccess Access & Algebraic Forms + + Access and streaming is similar to that for the cubic spline. + + @subsection cubicPic Illustration + + @image html tension_splines.png + +@section unitTests Unit Tests + + - src/test/polynomials.cpp + - src/test/cubic_splines.cpp + - src/test/smooth_linear_splines.cpp + - src/test/tension_function.cpp + - src/test/tension_splines.cpp + +@section ChangeLog + + - Jul 09 : ecl::SmoothLinearSpline is a a smoothed, linearly blend spline (with quintics). + - May 09 : ecl::blueprints::C2TensionSpline is a c2 continuous tension spline interpolation. + - May 09 : ecl::TensionSpline is a representation for a tension spline. + - May 09 : ecl::TensionFunction is a representation for a tension function. + - May 09 : ecl::blueprints::C2CubicSpline is a special case of the C2CubicSpline, the natural cubic spline. + - May 09 : ecl::blueprints::C2CubicSpline is a blueprint for C2 continous splines over a set of data. + - May 09 : ecl::blueprints::DerivativeHeuristicCubicSpline uses an automated velocity based heuristic to generate a cubic spline on a data set. + - May 09 : ecl::BluePrintFactory is a blueprint factory for cubic splines. + - May 09 : ecl::CubicSpline is a typedef'd representation for a cubic spline. +**/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/doxygen/tension_splines.png b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/tension_splines.png new file mode 100644 index 0000000..2f67409 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_geometry/doxygen/tension_splines.png differ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..d9dd383 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(geometry) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry.hpp new file mode 100644 index 0000000..53a2f0d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry.hpp @@ -0,0 +1,43 @@ +/** + * @file /include/ecl/geometry.hpp + * + * @brief Mathematical tools for geometry. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_HPP_ +#define ECL_GEOMETRY_HPP_ + +/***************************************************************************** +** Eigen's Geometry Module +*****************************************************************************/ + +#include + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "geometry/macros.hpp" +#include "geometry/angle.hpp" +#include "geometry/cartesian_point.hpp" +#include "geometry/cubic_spline.hpp" +#include "geometry/function_math.hpp" +#include "geometry/homogeneous_point.hpp" +#include "geometry/pascals_triangle.hpp" +#include "geometry/polynomial.hpp" +#include "geometry/pose2d.hpp" +#include "geometry/smooth_linear_spline.hpp" +#include "geometry/spline_function.hpp" +#include "geometry/tension_function.hpp" +#include "geometry/tension_spline.hpp" +#include "geometry/odometry.hpp" + +#endif /*ECL_GEOMETRY_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/CMakeLists.txt new file mode 100644 index 0000000..5522b4a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/geometry) + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/angle.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/angle.hpp new file mode 100644 index 0000000..712cff2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/angle.hpp @@ -0,0 +1,426 @@ +/** + * @file /include/ecl/geometry/angle.hpp + * + * @brief C++ interface for angles (degrees/radians). + * + * @date February 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_ANGLE_HPP_ +#define ECL_GEOMETRY_ANGLE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Converts radians to degrees and returns the result. + * + * @param radians : input value in radians (float or double type). + * @param dummy : ignore this, is used for sfinae concept. + * @return T : the angle in degrees. + */ +template +ecl_geometry_PUBLIC T radians_to_degrees(const T &radians, typename enable_if >::type* dummy = 0) { + (void)dummy; + static const T rads_to_degs = 180.0/pi; + return radians*rads_to_degs; +} + +/** + * @brief Converts degrees to radians and returns the result. + * + * @param degrees : input value in degrees (float or double type). + * @param dummy : ignore this, is used for sfinae concept. + * @return T : the angle in radians. + */ +template +ecl_geometry_PUBLIC T degrees_to_radians(const T °rees, typename enable_if >::type* dummy = 0) { + (void)dummy; + static const T degs_to_rads = pi/180.0; + return degrees*degs_to_rads; +} + +/** + * @brief Wrap the angle on -pi,pi (float types). + * + * This uses the float versions of the math functions to wrap + * the angle on -pi, pi. This is the fast version which + * acts on the input variable. + * + * @param angle : the angle to be wrapped. + */ +ecl_geometry_PUBLIC const float& wrap_angle(float &angle); + +/** + * @brief Return the wrapped the angle on -pi,pi (float types). + * + * This uses the float versions of the math functions to wrap + * the angle on -pi, pi. This is the slow version which creates + * a copy and returns it. + * + * @param angle : the angle to be wrapped. + * @return float : the wrapped angle. + */ +ecl_geometry_PUBLIC float wrap_angle(const float &angle); +/** + * @brief Wrap the angle on -pi,pi (double types). + * + * This uses the double versions of the math functions to wrap + * the angle on -pi, pi. This is the fast version which + * acts on the input variable. + * + * @param angle : the angle to be wrapped. + */ +ecl_geometry_PUBLIC const double& wrap_angle(double &angle); + +/** + * @brief Return the wrapped the angle on -pi,pi (double types). + * + * This uses the double versions of the math functions to wrap + * the angle on -pi, pi. This is the slow version which creates + * a copy and returns it. + * + * @param angle : the angle to be wrapped. + * @return double : the wrapped angle. + */ +ecl_geometry_PUBLIC double wrap_angle(const double &angle); + +/***************************************************************************** +** Interface [Angle] +*****************************************************************************/ +/** + * @brief Parent template definition for angles. + * + * Do not use this directly. Use the specialisations instead. + */ +template +class ecl_geometry_PUBLIC Angle { +private: + /** + * @brief Prevents usage of this template class directly. + * + * This class isn't yet intended for generic use - use the specialisations + * instead. + */ + Angle() {}; +}; + +/** + * @brief Interface for angular measurements. + * + * This is a simple interface designed for scientific calculations (thus + * the default format is in radians). It allows free interaction with + * float types, does automatic wrapping on [-pi, pi] under the hood and + * provides some generic methods for conversions and wrapping on + * plain double types. + * + * @tparam T : must be a float type (e.g. float, double, float32, float64) + */ +template +class ecl_geometry_PUBLIC Angle >::type> { +public: + /********************* + ** Typedefs + **********************/ + typedef ecl::linear_algebra::Matrix RotationMatrix; + /** + * @brief Constructs an angle in radians. + * + * Configures the angle from the input double value. Automatically wraps + * this value if it doesn't fall within [-pi,pi]. + * + * @param angle : input angle (radians). + */ + Angle(const T &angle = 0.0) : value(angle) { wrap_angle(value); } + /** + * @brief Construct from a 2x2 rotation matrix. + * @param rotation : input rotation matrix. + */ + Angle(const RotationMatrix &rotation) { + value = std::atan2(rotation(1,0),rotation(0,0)); + } + + /** + * @brief Allow assignment from float types. + * + * This allows convenient assignment from float types. It does + * automatic wrapping on the input value. + * + * @param angle : input angle (radians). + * @return Angle : the wrapped angle instance. + */ + const Angle& operator=(const T &angle); + /********************* + ** Math Operators + **********************/ + /** + * @brief Sum operator. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to add (radians). + * @return Angle : the wrapped angle instance. + */ + Angle operator+(const T &angle) const; + /** + * @brief Sum operator. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to add (radians). + * @return Angle : the wrapped angle instance. + */ + Angle operator+(const Angle &angle) const; + /** + * @brief Sum operator that works on this instance. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to add (radians). + */ + void operator+=(const T &angle); + /** + * @brief Sum operator that works on this instance. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to add (radians). + */ + void operator+=(const Angle &angle); + /** + * @brief Difference operator. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to subtract (radians). + * @return Angle : the wrapped angle instance. + */ + Angle operator-(const T &angle) const; + /** + * @brief Difference operator. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to subtract (radians). + * @return Angle : the wrapped angle instance. + */ + Angle operator-(const Angle &angle) const; + /** + * @brief Difference operator that works on this instance. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to subtract (radians). + */ + void operator-=(const T &angle); + /** + * @brief Difference operator that works on this instance. + * + * Note this also ensures the angle is wrapped. + * + * @param angle : angle to subtract (radians). + */ + void operator-=(const Angle &angle); + /** + * @brief Multiplier. + * + * Note this also ensures the angle is wrapped. + * + * @param scalar : scalar multipler to apply. + * @return Angle : the wrapped angle instance. + */ + Angle operator*(const T &scalar) const; + /** + * @brief Multiplier that works on this instance. + * + * Note this also ensures the angle is wrapped. + * + * @param scalar : scalar multipler to apply. + */ + void operator*=(const T &scalar); + + /********************* + ** Casting + **********************/ + /** + * @brief Convenient equivalence to the c/c++ float type. + * + * Allows for easy manipulation, especially within calculations. This + * breaks the rule which dictates that we should never use them + * as they create uncertainty about an object. Here it's just + * ridiculously convenient and more to the point, intuitive, + * so we do so. + */ + operator const T&() const { return value; } + /** + * @brief Returns the value of the angle in unit degrees. + * + * This does not change the internal formatting for the angle + * (which is in radians). It simply returns its equivalent + * in unit degrees. The returned value will be wrapped + * on [-180, 180]. + * + * @return T : the angle in degrees. + */ + T degrees(); + + /** + * @brief Convert to a 2x2 rotation matrix. + * @return RotationMatrix : representation as a 2x2 rotation matrix. + */ + RotationMatrix rotationMatrix() const { + T c = std::cos(value); + T s = std::sin(value); + return (RotationMatrix() << c, -s, s, c).finished(); + } + + /** + * @brief Generates an angle instance from an angle in degrees. + * + * Generates an angle specified in degrees as a double to + * a fully constructed Angle instance. + * + * @code + * Angle angle = Angle::Degrees(45); + * @endcode + * + * @param angle : the angle (degrees). + * @return Angle : the constructed instance. + */ + static Angle Degrees(const T &angle); + /** + * @brief Generates an angle instance from an angle in radians. + * + * Generates an angle specified in radians as a double to a + * fully constructed Angle instance. + * + * @code + * Angle angle = Angle::Radians(ecl::math::pi); + * @endcode + * + * @param angle : the angle (radians). + * @return Angle : the constructed instance. + */ + static Angle Radians(const T &angle); + +private: + T value; +}; + +/** + * This template magic mucks up the doxy a bit. + * @cond DO_NOT_DOXYGEN + */ +/***************************************************************************** +** Implementation +*****************************************************************************/ + +template +T Angle >::type>::degrees() { + return radians_to_degrees(value); +} + +template +const Angle& Angle >::type>::operator=(const T &angle) { + value = angle; + wrap_angle(value); + return *this; +} + +/***************************************************************************** +** Operators +*****************************************************************************/ + +template +Angle Angle >::type>::operator+(const T &angle) const { + return Angle(wrap_angle(value+angle)); +} + +template +Angle Angle >::type>::operator+(const Angle &angle) const { + return Angle(wrap_angle(value+angle.value)); +} + +template +void Angle >::type>::operator+=(const T &angle) { + value += angle; + wrap_angle(value); +} + +template +void Angle >::type>::operator+=(const Angle &angle) { + value += angle.value; + wrap_angle(value); +} + +template +Angle Angle >::type>::operator-(const T &angle) const { + return Angle(wrap_angle(value-angle)); +} + +template +Angle Angle >::type>::operator-(const Angle &angle) const { + return Angle(wrap_angle(value-angle.value)); +} + +template +void Angle >::type>::operator-=(const T &angle) { + value -= angle; + wrap_angle(value); +} + +template +void Angle >::type>::operator-=(const Angle &angle) { + value -= angle.value; + wrap_angle(value); +} + +template +Angle Angle >::type>::operator*(const T &scalar) const { + return Angle(wrap_angle(scalar*value)); +} + +template +void Angle >::type>::operator*=(const T &scalar) { + value *= scalar; + wrap_angle(value); +} + +/***************************************************************************** +** Statics +*****************************************************************************/ + +template +Angle Angle >::type>::Degrees(const T &angle) { + return Angle(degrees_to_radians(angle)); +} + +template +Angle Angle >::type>::Radians(const T &angle) { + return Angle(angle); +} +/** + * @endcond + */ + +} // namespace ecl + +#endif /* ECL_GEOMETRY_ANGLE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cartesian_point.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cartesian_point.hpp new file mode 100644 index 0000000..aafa2fd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cartesian_point.hpp @@ -0,0 +1,521 @@ +/** + * @file /include/ecl/geometry/cartesian_point.hpp + * + * @brief Cartesian point representations. + * + * Im still not real certain about the usefulness of this class. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_CARTESIAN_POINT_HPP_ +#define ECL_GEOMETRY_CARTESIAN_POINT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [CartesianPoint] +*****************************************************************************/ +/** + * @brief Generic container storing a cartesian point of dimension N. + * + * This simply stores a cartesian point as a vector of dimension N. + * + * @tparam T : the underlying element type. + * @tparam N : the dimension. + * + * @sa CartesianPoint, CartesianPoint. + */ +template +class ECL_PUBLIC CartesianPoint { +public: + /** + * @brief Default constructor - sets all elements to the same value. + */ + CartesianPoint(const T &value = T()) : elements(ecl::linear_algebra::Matrix::Constant(value)) {} + /** + * @brief Initialises with the specified eigen style vector. + * + * @param point_vector : input eigen style vector. + */ + CartesianPoint(const ecl::linear_algebra::Matrix &point_vector) : elements(point_vector) {} + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying elements and then leaves the initialiser to + * do the rest. + * + * @code + * CartesianPoint point; // At this point it is initialised with default values. + * point << 1.0,2.0,3.0; + * @endcode + * + * @param value : the first of three points to enter. + * @return CommaInitialiser : eigen's comma initialiser mechanism. + */ + ecl::linear_algebra::CommaInitializer< ecl::linear_algebra::Matrix > operator<<(const T &value) { + return elements.operator<<(value); + } + + /** + * @brief Array like accessor. + * + * @param index : idnex of the element to access. + * @return T& : handle to the underlying element. + * @exception StandardException : throws if the index is outside of the array range [debug mode only]. + */ + T& operator [](const unsigned int& index) { + ecl_assert_throw( index : a reference to the underlying storage container. + */ + ecl::linear_algebra::Matrix& positionVector() { return elements; } + /** + * @brief Representation of the position vector in const eigen vector format. + * + * Converts representation to a const eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + const ecl::linear_algebra::Matrix& positionVector() const { return elements; } + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Matrix elements; +}; + +/***************************************************************************** +** Interface [CartesianPoint] +*****************************************************************************/ +/** + * @brief Specialisation for a cartesian point of dimension 3. + * + * It introduces handles to x(), y(), z() for convenience, whilst still + * permitting a vector representation of the underlying storage container + * via the positionVector() method. + * + * @tparam T : the underlying element type. + * + * @sa CartesianPoint3d, CartesianPoint3f, CartesianPoint3i. + */ +template +class ECL_PUBLIC CartesianPoint { +public: + /** + * @brief Default constructor - sets all elements to the same value. + */ + CartesianPoint(const T &value = T()) : elements(ecl::linear_algebra::Matrix::Constant(value)) {} + /** + * @brief Initialises with the specified eigen style vector. + * + * @param vec : input three dimensional eigen style vector. + */ + CartesianPoint(const ecl::linear_algebra::Matrix &vec) : elements(vec) {} + /** + * @brief Initialises the point with the specified values. + * + * @param x_i : x co-ordinate. + * @param y_i : y co-ordinate. + * @param z_i : z co-ordinate. + */ + CartesianPoint(const T &x_i, const T &y_i, const T &z_i) { + elements << x_i, y_i, z_i; + } + + virtual ~CartesianPoint() {} + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying elements and then leaves the initialiser to + * do the rest. + * + * @code + * CartesianPoint point; // At this point it is initialised with default values. + * point << 1.0,2.0,3.0; + * @endcode + * + * @param value : the first of three points to enter. + * @return CommaInitialiser : eigen's comma initialiser mechanism. + */ + ecl::linear_algebra::CommaInitializer< ecl::linear_algebra::Matrix > operator<<(const T &value) { + return elements.operator<<(value); + } + + /** + * @brief Representation of the position vector in eigen vector format. + * + * Converts representation to an eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + ecl::linear_algebra::Matrix& positionVector() { return elements; } + + /** + * @brief Representation of the position vector in const eigen vector format. + * + * Converts representation to a const eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + const ecl::linear_algebra::Matrix& positionVector() const { return elements; } + + /** + * @brief Size/dimension of the cartesian point. + * + * Size/dimension of the cartesian point. + * + * @return unsigned int : size/dimension. + */ + unsigned int size() { return 3; } + + /** + * @brief Returns a constant reference to the x co-ordinate. + * + * @return const T& : x value. + */ + const T& x() const { return elements[0]; } + /** + * @brief Returns a constant reference to the y co-ordinate. + * + * @return const T& : y value. + */ + const T& y() const { return elements[1]; } + /** + * @brief Returns a constant reference to the z co-ordinate. + * + * @return const T& : z value. + */ + const T& z() const { return elements[2]; } + /** + * @brief Returns a copy of the x co-ordinate. + * + * @return T : x value. + */ + T x() { return elements[0]; } + /** + * @brief Returns a copy of the y co-ordinate. + * + * @return T : y value. + */ + T y() { return elements[1]; } + /** + * @brief Returns a copy of the z co-ordinate. + * + * @return T : z value. + */ + T z() { return elements[2]; } + + void x(const T& value) { elements[0] = value; } /**< @brief Sets the x-coordinate. **/ + void y(const T& value) { elements[1] = value; } /**< @brief Sets the y-coordinate. **/ + void z(const T& value) { elements[2] = value; } /**< @brief Sets the z-coordinate. **/ + + template + friend OutputStream& operator<<(OutputStream &ostream , const CartesianPoint &point); + +private: + ecl::linear_algebra::Matrix elements; +}; + +typedef CartesianPoint CartesianPoint3d; /**< @brief Eigen style convenience handle for x, y, z triples in double format. **/ +typedef CartesianPoint CartesianPoint3f; /**< @brief Eigen style convenience handle for x, y, z triples in float format. **/ +typedef CartesianPoint CartesianPoint3i; /**< @brief Eigen style convenience handle for x, y, z triples in integer format. **/ + +/********************* +** Streaming +**********************/ +/** + * Insertion operator for sending the point to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param point : the point to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ +template +OutputStream& operator<<(OutputStream &ostream , const CartesianPoint &point) { + ostream << "[ " << point.x() << " " << point.y() << " " << point.z() << " ]"; + return ostream; +} + +/***************************************************************************** +** Interface [CartesianPoint] +*****************************************************************************/ +/** + * @brief Specialisation for a cartesian point of dimension 2. + * + * It introduces handles to x(), y(), z() for convenience, whilst still + * permitting a vector representation of the underlying storage container + * via the positionVector() method. + * + * @tparam T : the underlying element type. + * + * @sa CartesianPoint2d, CartesianPoint2f, CartesianPoint2i. + */ +template +class ECL_PUBLIC CartesianPoint { +public: + /** + * @brief Default constructor - sets all elements to the same value. + */ + CartesianPoint(const T &value = T()) : elements(ecl::linear_algebra::Matrix::Constant(value)) {} + /** + * @brief Initialises with the specified input vector. + * + * @param vec : input three dimensional vector. + */ + CartesianPoint(const ecl::linear_algebra::Matrix &vec) : elements(vec) {} + /** + * @brief Default copy constructor. + * + * @param point : copy this point directly. + */ + CartesianPoint(const CartesianPoint &point ) : elements( point.positionVector() ) {} + + CartesianPoint(const T &x_i, const T &y_i) { + elements << x_i, y_i; + } + + virtual ~CartesianPoint() {} + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying elements and then leaves the initialiser to + * do the rest. The initialiser will do range checking if NDEBUG is not defined. + * + * @code + * CartesianPoint point; // At this point it is initialised with default values. + * point << 1.0,2.0,2.0; // If NDEBUG is not defined, this will throw if you exceed the range. + * @endcode + * + * @param value : the first of three points to enter. + * @return BoundedListInitialiser : the comma initialiser mechanism. + */ + ecl::linear_algebra::CommaInitializer< ecl::linear_algebra::Matrix > operator<<(const T &value) { + return elements.operator<<(value); + } + + T& operator [](const unsigned int& index) { + ecl_assert_throw( index<2, StandardException(LOC,OutOfRangeError)); + return elements[index]; + } + + const T operator [](const unsigned int& index) const { + ecl_assert_throw( index<2, StandardException(LOC,OutOfRangeError)); + return elements[index]; + } + + const CartesianPoint & operator = (const CartesianPoint &v) + { + elements = v.positionVector(); + return *this; + } + /** + * @brief Representation of the position vector in eigen vector format. + * + * Converts representation to an eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + ecl::linear_algebra::Matrix& positionVector() { return elements; } + + /** + * @brief Representation of the position vector in const eigen vector format. + * + * Converts representation to a const eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + const ecl::linear_algebra::Matrix& positionVector() const { return elements; } + + /** + * @brief Size/dimension of the cartesian point. + * + * Size/dimension of the cartesian point. + * + * @return unsigned int : size/dimension. + */ + unsigned int size() { return 2; } + + /** + * @brief Returns a constant reference to the x co-ordinate. + * + * @return const T& : x value. + */ + const T& x() const { return elements[0]; } + /** + * @brief Returns a constant reference to the y co-ordinate. + * + * @return const T& : y value. + */ + const T& y() const { return elements[1]; } + /** + * @brief Returns a copy of the x co-ordinate. + * + * @return T : x value. + */ + T x() { return elements[0]; } + /** + * @brief Returns a copy of the y co-ordinate. + * + * @return T : y value. + */ + T y() { return elements[1]; } + + bool operator == (const CartesianPoint & other ) const + { + if( other.x() != x() || other.y() != y() ) return false; + else return true; + } + + bool operator != (const CartesianPoint & other ) const + { + if( other.x() != x() || other.y() != y() ) return true; + else return false; + } + + void rotate( const double & angle ) + { + double c = cos(angle); + double s = sin(angle); + double tx = x()*c - y()*s; + double ty = x()*s + y()*c; + + elements[0] = tx; + elements[1] = ty; + } + + double get_angle(void) + { + return atan2( y(), x() ); + } + + void operator += ( const CartesianPoint & other ) + { + elements += other.positionVector(); + } + + T distance ( const CartesianPoint & other ) + { + ecl::linear_algebra::Matrix temp_element = elements - other.positionVector(); + return static_cast( sqrt( temp_element[0]*temp_element[0]+temp_element[1]*temp_element[1]) ); + } + + T Normalize(void) + { + T mag = ecl::EuclideanNorm()( x(), y() ); +// T mag = static_cast(sqrt( x()*x()+y()*y() )); + if ( mag == static_cast(0) ) // make a unit vector in z-direction + { + elements[0] = 1.0; + elements[1] = 0.0; + } else + { + elements[0] *= (1.0/mag); + elements[1] *= (1.0/mag); + } + return mag; + } + + CartesianPoint operator * (double d) const + { + return CartesianPoint( elements*d ); + } + + CartesianPoint operator + (const CartesianPoint &v) const + { + return CartesianPoint( x()+v.x(), y()+v.y() ); + } + + CartesianPoint operator - (const CartesianPoint &v) const + { + return CartesianPoint( x()-v.x(), y()-v.y() ); + } + + double Norm(void) + { + return static_cast( ecl::EuclideanNorm()( x(), y() ) ); +// return (sqrt( x()*x()+y()*y() )); + } + + void x(const T& value) { elements[0] = value; } /**< @brief Sets the x-cor.dinate. **/ + void y(const T& value) { elements[1] = value; } /**< @brief Sets the y-cordinate. **/ + + template + friend OutputStream& operator<<(OutputStream &ostream , const CartesianPoint &point); + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Matrix elements; +}; + +typedef CartesianPoint CartesianPoint2d; /**< @brief Eigen style convenience handle for x, y, z triples in double format. **/ +typedef CartesianPoint CartesianPoint2f; /**< @brief Eigen style convenience handle for x, y, z triples in float format. **/ +typedef CartesianPoint CartesianPoint2i; /**< @brief Eigen style convenience handle for x, y, z triples in integer format. **/ + +/********************* +** Streaming +**********************/ +/** + * Insertion operator for sending the array to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param point : the point to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ +template +OutputStream& operator<<(OutputStream &ostream , const CartesianPoint &point) { + ostream << "[ " << point.x() << " " << point.y() << " ]"; + return ostream; +} + +} // namespace ecl + +#endif /* ECL_GEOMETRY_CARTESIAN_POINT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cubic_spline.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cubic_spline.hpp new file mode 100644 index 0000000..aac50db --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/cubic_spline.hpp @@ -0,0 +1,419 @@ +/** + * @file /include/ecl/geometry/cubic_spline.hpp + * + * @brief Storage container for a cubic spline interpolation. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_CUBIC_SPLINE_HPP_ +#define ECL_GEOMETRY_CUBIC_SPLINE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "polynomial.hpp" +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +class CubicSpline; + +namespace blueprints { + +class C2CubicSpline; +class DerivativeHeuristicCubicSpline; + +} // namespace blueprints + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ +/** + * @brief Blueprint factory for cubic splines. + * + * Generates various blueprints that instantiate or configure cubic splines from commonly + * used algorithms. + * + * @sa @ref ecl::CubicSpline "CubicSpline". + */ +template<> +class ECL_PUBLIC BluePrintFactory< CubicSpline > { + public: + /** + * @brief Cubic spline blueprint satisfying y, y' and y'' continuity with y''_0 = y''_f = 0. + * + * This is a special case of the ContinuousDerivatives blueprint that uses + * y''_0 = y''_f = 0 boundary conditions instead. It is more commonly referred to + * as the natural cubic spline. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @return C2CubicSpline : the resulting blueprint. + */ + static blueprints::C2CubicSpline Natural(const Array& x_set, const Array& y_set); + /** + * @brief Cubic spline blueprint satisfying y, y' and y'' continuity requirements. + * + * Generates a blueprint for creating cubic splines on a set of data + * satisfying the constraints of continuity for y, y' and y''. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param ydot_0 : initial derivative value (boundary constraint). + * @param ydot_f : final derivative value (boundary constraint). + * @return C2CubicSpline : the resulting blueprint. + */ + static blueprints::C2CubicSpline ContinuousDerivatives( + const Array& x_set, const Array& y_set, const double ydot_0, const double ydot_f); + /** + * @brief Cubic spline blueprint derived from a y' heuristic. + * + * Generates a blueprint for creating cubic splines on a set of data + * satisfying a heuristic that automatically generates derivatives at the + * via points. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param ydot_0 : initial derivative value (boundary constraint). + * @param ydot_f : final derivative value (boundary constraint). + * @return DerivativeHeuristicCubicSpline : the resulting blueprint. + */ + static blueprints::DerivativeHeuristicCubicSpline DerivativeHeuristic( + const Array& x_set, const Array& y_set, const double ydot_0, const double ydot_f); + + virtual ~BluePrintFactory() {} +}; + +/***************************************************************************** +** Interface [CubicSpline] +*****************************************************************************/ +/** + * @brief Storage container for a cubic spline interpolation. + * + * Storage container for a cubic spline interpolation. This is a very standard + * cubic spline container. Use the corresponding blueprints for + * construction of the splines. + * + * There are various ways of constructing the cubic spline, though almost always + * a C1 or C2 continuous function is desired. To achieve this, either a heuristic + * or a C2 constraint can be fixed, resulting in a derivation for the spline's + * functions. + * + * @sa @ref ecl::Polynomial "Polynomial", @ref splinesGeometry "Math::Splines. + **/ +class ECL_PUBLIC CubicSpline : public BluePrintFactory< CubicSpline > { + public: + /****************************************** + ** Constructors + *******************************************/ + /** + * @brief Default constructor. + * + * Default constructor. + **/ + CubicSpline () {}; + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * Array x_set(5); + * Array y_set(5); + * x_set = 0.0, 1.0, 2.0, 3.0, 4.0; + * y_set = 1.0, 2.0, 1.0, 3.0, 4.0; + * CubicSpline cubic_spline = CubicSpline::Natural(x_set,y_set); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * CubicSpline cubic_spline; + * cubic_spline = CubicSpline::Natural(x_set,y_set); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprints concept (refer to ecl_concepts' documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa ecl::utilities::BluePrintFactory. + */ + template + CubicSpline(const BluePrint< Derived > &blueprint) { + blueprint.implementApply(*this); + } + virtual ~CubicSpline () {}; + + /****************************************** + ** Access + *******************************************/ + friend class blueprints::DerivativeHeuristicCubicSpline; + friend class blueprints::C2CubicSpline; + /** + * @brief Spline function. + * + * Extract the spline function's value at the indicated location. + * @param x : the domain value. + * @return double : the spline function's value. + * @exception : StandardException : throws if input x value is outside the spline range [debug mode only]. + */ + double operator()(const double &x) const; + /** + * @brief Spline derivative. + * + * Extract the derivative of the spline at the indicated value. + * @param x : the domain value. + * @return double : the derivative of the spline. + * @exception : StandardException : throws if input x value is outside the spline range [debug mode only]. + */ + double derivative(double x) const; + /** + * @brief Spline second derivative. + * + * Extract the second derivative of the spline. + * @param x : the domain value. + * @return double : the second derivative of the spline. + * @exception : StandardException : throws if input x value is outside the spline range [debug mode only]. + */ + double dderivative(double x) const; + + /** + * @brief The discretised domain for this spline. + * + * This returns the array of discretised time values that define + * the domains of each polynomial within the spline. + * @return const Array& : the discretised domain. + */ + const Array& domain() { return discretised_domain; } + /** + * @brief The polynomial sequence. + * + * This returns a handle to the array of cubic polynomials + * that make up the spline. + * + * @return const Array& : the polynomial sequence. + */ + const Array& polynomials() { return cubic_polynomials; } + + /****************************************** + ** Streaming + *******************************************/ + /** + * @brief Streaming output insertion operator for for cubic splines. + * + * Streaming output insertion operator for cubic splines. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param cubic_spline : the cubic spline. + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, const CubicSpline &cubic_spline); + + private: + Array discretised_domain; // N+1 x_i's + // Would normally use pointers here, but the polynomials have fixed storage + // size, the copy cost is small and the access times will be faster this way. + Array cubic_polynomials; // N polynomials +}; + +/***************************************************************************** +** Implementation [CubicSpline][Streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, const CubicSpline &cubic_spline) { + + ecl_compile_time_concept_check(StreamConcept); + + for ( unsigned int i = 0; i < cubic_spline.cubic_polynomials.size(); ++i ) { + ostream << cubic_spline.cubic_polynomials[i] << "\n"; + } + ostream.flush(); + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [C2CubicSpline] +*****************************************************************************/ + +/** + * @brief Blueprint for generating a cubic spline satisfying C2 constraints. + * + * Blueprint for generating a cubic spline on a set of data given the constraint + * of continuity of y, y' and y''. + * + * @sa @ref ecl::CubicSpline "CubicSpline". + * + **/ +class ECL_PUBLIC C2CubicSpline : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::CubicSpline base_type; + /** + * @brief Default constructor. + * + * Default constructor (only utilised by the blueprint compile time assert). + */ + C2CubicSpline() {}; + + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * The constructor uses the input data sets to generate second derivatives + * at each via point so that a cubic spline will guarantee continuity. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param ydot_0 : initial derivative value (boundary constraint). + * @param ydot_f : final derivative value (boundary constraint). + * @exception : StandardException : throws if it failed to construct [debug mode only]. + */ + C2CubicSpline(const ecl::Array& x_set, const ecl::Array& y_set, + const double ydot_0, const double ydot_f); + + virtual ~C2CubicSpline() {}; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * The constructor uses the input data sets to generate second derivatives + * at each via point so that a cubic spline will guarantee continuity. This is + * a special case that does not use boundary derivative values to establish + * the result. Rather it automatically sets the boundary second derivatives + * to zero. This is more commonly known as the natural cubic spline. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @exception : StandardException : throws if it failed to construct [debug mode only]. + */ + C2CubicSpline(const ecl::Array& x_set, const ecl::Array& y_set); + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new cubic spline generated from the supplied data set. + * + * @return CubicSpline : a copy of the generated cubic spline. + */ + ecl::CubicSpline instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the data set to generate the configuration required for the cubic spline. + * + * @param spline : the spline to configure from the supplied data set. + */ + void apply(ecl::CubicSpline& spline) const; + + private: + ecl::Array x_data; + ecl::Array y_data; + ecl::Array yddot_data; +}; + +/***************************************************************************** +** Interface [DerivativeHeuristicCubicSpline] +*****************************************************************************/ + +/** + * @brief Blueprint for generating a cubic spline satisfying C2 constraints. + * + * Generates a blueprint for creating cubic splines on a set of data + * satisfying a heuristic that automatically generates y' values at the + * via points. These are later used to generate the connecting cubics. + * + * The heuristic finds the average of the linear slopes + * connected to each via point. This specifies the desired slope for that + * via point. + * + * @sa @ref ecl::CubicSpline "CubicSpline". + * + **/ +class ECL_PUBLIC DerivativeHeuristicCubicSpline : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::CubicSpline base_type; + /** + * @brief Default constructor. + * + * Default constructor (only utilised by the blueprint compile time assert). + */ + DerivativeHeuristicCubicSpline() {}; + + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * This constructor uses the heuristic to specify the slope at via points. + * These are stored and later used to generate the connecting cubics. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param ydot_0 : initial derivative value (boundary constraint). + * @param ydot_f : final derivative value (boundary constraint). + * + * @exception : StandardException : throws if it failed to construct [debug mode only]. + */ + DerivativeHeuristicCubicSpline(const ecl::Array& x_set, const ecl::Array& y_set, + const double ydot_0, const double ydot_f); + + virtual ~DerivativeHeuristicCubicSpline() {}; + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new cubic spline generated from the supplied data set. + * + * @return CubicSpline : a copy of the generated cubic spline. + */ + ecl::CubicSpline instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the data set to generate the configuration required for the cubic spline. + * + * @param spline : the spline to configure from the supplied data set. + */ + void apply(ecl::CubicSpline& spline) const; + + private: + ecl::Array x_data; + ecl::Array y_data; + ecl::Array ydot_data; +}; + +} // namespace blueprints +} // namespace ecl + +#endif /* ECL_GEOMETRY_CUBIC_SPLINE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/function_math.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/function_math.hpp new file mode 100644 index 0000000..b250e23 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/function_math.hpp @@ -0,0 +1,132 @@ +/** + * @file /include/ecl/geometry/function_math.hpp + * + * @brief Functors for evaluating various mathematical properties of functions. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_FUNCTION_MATH_HPP_ +#define ECL_GEOMETRY_FUNCTION_MATH_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Factory +*****************************************************************************/ +/** + * @brief Used as a parent to load function math into function classes. + * + * Used a bit like the blueprint factory for polynomials. Implementation is in + * the specialisations (if it has any). + */ +template +class ECL_PUBLIC FunctionMath { +public: + /** + * @brief Default empty constructor (loads no math). + */ + FunctionMath() {}; + virtual ~FunctionMath() {}; +}; + +/***************************************************************************** +** Maximum/Minimum +*****************************************************************************/ + +/** + * @brief Primary template functor for the maximum of a continuous function. + * + * Maximum of a continuous function on a bounded interval. This functor + * is only a primary template, the specialisations do the actual work. Consequently + * this class cannot be instantiated directly. + * + * @sa Maximum, Maximum. + **/ +template +class ECL_LOCAL Maximum { +private: + /** + * @brief Private constructor - prevents instantiation of this primary template. + */ + Maximum() {}; + virtual ~Maximum() {}; +}; + + +/** + * @brief Primary template functor for the minimum of a continuous function. + * + * Minimum of a continuous function on a bounded interval. This functor + * is only a primary template, the specialisations do the actual work. Consequently + * this class cannot be instantiated directly. + * + * @sa Minimum, Minimum. + **/ +template +class ECL_LOCAL Minimum { +private: + /** + * @brief Private constructor - prevents instantiation of this primary template. + */ + Minimum() {}; + virtual ~Minimum() {}; +}; + + +/** + * @brief Primary template functor for the intersection of like functions. + **/ +template +class ECL_LOCAL Intersection { +private: + /** + * @brief Private constructor - prevents instantiation of this primary template. + */ + Intersection() {}; + virtual ~Intersection() {}; +}; + +/** + * @brief Primary template functor for polynomial division. + **/ +template +class ECL_LOCAL Division { +private: + /** + * @brief Private constructor - prevents instantiation of this primary template. + */ + Division() {}; + virtual ~Division() {}; +}; + +/** + * @brief Primary template functor for the roots of a function (x-axis intercepts). + **/ +template +class ECL_LOCAL Roots { +private: + /** + * @brief Private constructor - prevents instantiation of this primary template. + */ + Roots() {}; + virtual ~Roots() {}; +}; + +} // namespace ecl + + +#endif /* ECL_GEOMETRY_FUNCTION_MATH_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/homogeneous_point.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/homogeneous_point.hpp new file mode 100644 index 0000000..2955454 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/homogeneous_point.hpp @@ -0,0 +1,207 @@ +/** + * @file /include/ecl/geometry/homogeneous_point.hpp + * + * @brief Real valued x-y-z point with homogeneous representation. + * + * Essentially a container that stores 4 floats with the last always being + * fixed at 1.0. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_HOMOGENEOUS_POINT_HPP_ +#define ECL_GEOMETRY_HOMOGENEOUS_POINT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [HomogeneousPoint] +*****************************************************************************/ +/** + * @brief Dummy parent class for Homogenous points. + * + * SFINAE trick to ensure that only floats are used for the template parameter. + * The real class is in the specialisation. + */ +template +class HomogeneousPoint : public ecl::FailedObject {}; + +/** + * @brief Container storing a homogenous point. + * + * Stores float x-y-z triples and a fourth element set to 1.0. + * + * @tparam T : the underlying element type - must be float. + */ +template +class HomogeneousPoint >::type> { +public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW // needed for 16B alignment + /** + * @brief Default constructor - sets all elements to the same value. + */ + HomogeneousPoint(const T &value = T()) { + elements.template block<3,1>(0,0) = ecl::linear_algebra::Matrix::Constant(value); + elements(3,0) = 1.0; + } + /** + * @brief Initialises with the specified eigen style vector. + * + * This only uses a partial vector (the remaining element gets + * automatically filled in as 1.0). + * + * @param vec : input three dimensional eigen style vector. + */ + HomogeneousPoint(const ecl::linear_algebra::Matrix &vec) { + elements.template block<3,1>(0,0) = vec; + elements[3] = 1.0; + } + /** + * @brief Initialises with the specified eigen style vector in homogeneous format. + * + * Takes the full vector in this case - last element must always be 1.0. + * + * @param vec : input three dimensional eigen style vector. + */ + HomogeneousPoint(const ecl::linear_algebra::Matrix &vec) : elements(vec) { + ecl_assert_throw(elements[3] == 1.0, ecl::StandardException(LOC,ecl::InvalidInputError)); + } + /** + * @brief Initialises the point with the specified values. + * + * @param x_i : x co-ordinate. + * @param y_i : y co-ordinate. + * @param z_i : z co-ordinate. + */ + HomogeneousPoint(const T &x_i, const T &y_i, const T &z_i) { + elements << x_i, y_i, z_i, 1.0; + } + + virtual ~HomogeneousPoint() {} + + /********************* + ** Assignment + **********************/ + /** + * Provides a comma initialisation facility. This initiates the comma initialiser + * with an iterator to the underlying elements and then leaves the initialiser to + * do the rest. + * + * @code + * HomogeneousPoint point; // At this point it is initialised with default values. + * point << 1.0,2.0,3.0,1.0; + * @endcode + * + * @param value : the first of three points + last point must be 1.0. + * @return CommaInitialiser : eigen's comma initialiser mechanism. + */ + ecl::linear_algebra::CommaInitializer< ecl::linear_algebra::Matrix > operator<<(const T &value) { + return elements.operator<<(value); + } + + /** + * @brief Representation of the position vector in eigen vector format. + * + * Converts representation to an eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + ecl::linear_algebra::Matrix& positionVector() { return elements; } + + /** + * @brief Representation of the position vector in const eigen vector format. + * + * Converts representation to a const eigen vector reference - oft + * necessary in mathematics calculations. + * @return Matrix : a reference to the underlying storage container. + */ + const ecl::linear_algebra::Matrix& positionVector() const { return elements; } + + /** + * @brief Returns a constant reference to the x co-ordinate. + * + * @return const T& : x value. + */ + const T& x() const { return elements[0]; } + /** + * @brief Returns a constant reference to the y co-ordinate. + * + * @return const T& : y value. + */ + const T& y() const { return elements[1]; } + /** + * @brief Returns a constant reference to the z co-ordinate. + * + * @return const T& : z value. + */ + const T& z() const { return elements[2]; } + /** + * @brief Returns a copy of the x co-ordinate. + * + * @return T : x value. + */ + T x() { return elements[0]; } + /** + * @brief Returns a copy of the y co-ordinate. + * + * @return T : y value. + */ + T y() { return elements[1]; } + /** + * @brief Returns a copy of the z co-ordinate. + * + * @return T : z value. + */ + T z() { return elements[2]; } + + void x(const T& value) { elements[0] = value; } /**< @brief Sets the x-coordinate. **/ + void y(const T& value) { elements[1] = value; } /**< @brief Sets the y-coordinate. **/ + void z(const T& value) { elements[2] = value; } /**< @brief Sets the z-coordinate. **/ + + template + friend OutputStream& operator<<(OutputStream &ostream , const HomogeneousPoint &point); + +private: + ecl::linear_algebra::Matrix elements; +}; + +typedef HomogeneousPoint HomogeneousPointf; /**< @brief Eigen style convenience handle for homogeneous points in float format. **/ +typedef HomogeneousPoint HomogeneousPointd; /**< @brief Eigen style convenience handle for homogeneous points in double format. **/ + +/********************* +** Streaming +**********************/ +/** + * Insertion operator for sending the point to an output stream. This + * is raw, and has no formatting. + * @param ostream : the output stream. + * @param point : the point to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ +template +OutputStream& operator<<(OutputStream &ostream , const HomogeneousPoint &point) { + ostream << "[ " << point.x() << " " << point.y() << " " << point.z() << " ]"; + return ostream; +} +} // namespace ecl + +#endif /* ECL_GEOMETRY_HOMOGENEOUS_POINT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose2d.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose2d.hpp new file mode 100644 index 0000000..eb93e3b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose2d.hpp @@ -0,0 +1,498 @@ +/** + * @file /ecl_geometry/include/ecl/geometry/pose2d.hpp + * + * @brief Pose representations. + * + * These are particularly suited for mobile robot representaitons. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_LEGACY_POSE2D_HPP_ +#define ECL_GEOMETRY_LEGACY_POSE2D_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "angle.hpp" + +/***************************************************************************** +** Enums +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Used by the traits to select the storage type for Pose2D classes. + */ +enum Pose2DStorageType { + RotationAngleStorage, //!< RotationAngleStorage + RotationMatrixStorage,//!< RotationMatrixStorage +}; + +} // namespace ecl + +/***************************************************************************** +** Forward declarations +*****************************************************************************/ + +namespace ecl { + +template class LegacyPose2D; + +} // namespace ecl + +/***************************************************************************** +** Traits +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Parent template for ecl traits of the pose classes. + */ +template +struct ecl_traits< LegacyPose2D > {}; + +/** + * @brief Traits for the pose2D class with rotation matrix storage. + */ +template +struct ecl_traits< LegacyPose2D > { +public: + typedef Float Scalar; /**< @brief Element type. **/ + typedef ecl::linear_algebra::Matrix RotationType; /**< @brief Rotation storage type (matrix). **/ +}; + +/** + * @brief Traits for the pose2D class with scalar angle storage. + */ +template +struct ecl_traits< LegacyPose2D > { +public: + typedef Float Scalar; /**< @brief Element type. **/ + typedef Angle RotationType; /**< @brief Rotation storage type (angle). **/ +}; + +} // namespace ecl + +/***************************************************************************** +** Operations +*****************************************************************************/ + +namespace ecl { +namespace geometry { + +/** + * @brief Parent template for the pose2D math classes. + */ +template class Pose2DMath {}; +/** + * @brief Math functions/selectors for the pose2D class with rotation matrix storage. + * + * This is a mechanism whereby the pose2D class can automatically select the + * appropriate math functionalities depending on storage, rotation matrix + * in this case. + */ +template +class ECL_PUBLIC Pose2DMath { +public: + typedef ecl::linear_algebra::Matrix RotationMatrixType; /**@brief Rotation matrix type for pose2D. **/ + + static RotationMatrixType Identity() { return RotationMatrixType::Identity(); } /**< @brief Zero rotation. **/ + static RotationMatrixType Rotation(const RotationMatrixType &rotation) { return rotation; } /**< @brief Arbitrary rotation converter. **/ + static RotationMatrixType Rotation(const Angle& angle) { return angle.rotationMatrix(); } /**< @brief Arbitrary rotation converter. **/ + static Angle Heading(const RotationMatrixType &rotation) { return Angle(rotation); } /**< @brief Arbitrary heading angle converter. **/ + static RotationMatrixType Product(const RotationMatrixType &rot1, const RotationMatrixType &rot2) { return rot1*rot2; } /**< @brief Overloaded product calculater for poses. **/ + static RotationMatrixType Product(const RotationMatrixType &rotation, const Angle &angle) { return rotation*angle.rotationMatrix(); } /**< @brief Overloaded product calculater for poses. **/ + static RotationMatrixType Inverse(const RotationMatrixType &rotation) { return rotation.transpose(); } /**< @brief Pose inverse, rotation matrix format. **/ +}; + +/** + * @brief Math functions/selectors for the pose2D class with rotation angle storage. + * + * This is a mechanism whereby the pose2D class can automatically select the + * appropriate math functionalities depending on storage, rotation angle + * in this case. + */ +template +class ECL_PUBLIC Pose2DMath { +public: + typedef ecl::linear_algebra::Matrix RotationMatrixType; /**@brief Rotation matrix type for pose2D. **/ + static Angle Identity() { return Angle(0.0); } /**< @brief Zero rotation. **/ + static Angle Rotation(const Angle& radians) { return Angle(radians); } /**< @brief Arbitrary rotation converter. **/ + static Angle Rotation(const RotationMatrixType &rotation) { return Pose2DMath::Heading(rotation); } /**< @brief Arbitrary rotation converter. **/ + static Angle Heading(const Angle &angle) { return angle; } /**< @brief Arbitrary heading angle converter. **/ + static Angle Product(const Angle &angle1, const Angle &angle2) { return angle1+angle2; } /**< @brief Overloaded product calculater for poses. **/ + static Angle Product(const Angle &angle, RotationMatrixType &rotation) { return angle + Angle(rotation); } /**< @brief Overloaded product calculater for poses. **/ + static Angle Inverse(const Angle &angle) { return Angle(-1*angle); } /**< @brief Pose inverse, angle format. **/ +}; + +} // namespace geometry +} // namespace ecl + + +/***************************************************************************** +** Pose2D +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Parent template definition for Pose2D. + * + * Do not use this directly. Use the specialisations instead. + */ +template +class ECL_PUBLIC LegacyPose2D { + typedef Float Scalar; +private: + LegacyPose2D() {}; /**< @brief Prevents usage of this template class directly. **/ +}; + +/** + * @brief Representation for a 2D pose (3 degrees of freedom). + * + * This represents a transformation typical of that of an object in 2D, + * e.g. a mobile robot on a horizontal plane. There are two storage + * types for this object, the default is rotation matrix, but scalar + * angular storage can be selected by supplying a second template + * parameter to the type: + * + * @code + * LegacyPose2D + * @endcode + * + * @tparam Float : must be a float type (e.g. float, double, float32, float64) + * @tparam Storage : type of storage (RotationMatrixStorage, RotationAngleStorage). + */ +template +class ECL_PUBLIC LegacyPose2D >::type> { +public: + /****************************************** + ** Eigen Alignment + *******************************************/ + EIGEN_MAKE_ALIGNED_OPERATOR_NEW // http://eigen.tuxfamily.org/dox/StructHavingEigenMembers.html + + /****************************************** + ** Typedef + *******************************************/ + typedef Float Scalar; /**< @brief Eigen style declaration of the element type. **/ + typedef geometry::Pose2DMath RotationMath; /**< @brief Rotational math specific to this storage type. **/ + typedef geometry::Pose2DMath RotationMatrixMath; /**< @brief Rotational math specific to rotational matrices. **/ + typedef geometry::Pose2DMath RotationAngleMath; /**< @brief Rotational math specific to rotational angles. **/ + typedef typename ecl_traits< LegacyPose2D >::type> >::RotationType RotationType; /**< @brief The type used for storage of the rotation/angle. **/ + typedef ecl::linear_algebra::Matrix RotationMatrix; /**< @brief The type used to represent rotation matrices. **/ + typedef ecl::linear_algebra::Matrix Translation; /**< @brief The type used to represent translations. **/ + + /****************************************** + ** Constructors + *******************************************/ + /** + * @brief Default constructor. + * + * Initialises the pose with zero rotation and zero translation. Might be worth + * dropping the setting here (aka eigen style) if we need speed, not safety. + * If we do so, maybe a debug mode is_initialised flag? Also, if we do so + * make sure to update the Identity static function. + */ + LegacyPose2D() : rot( RotationMath::Identity()), trans(Translation::Zero()) {} + + /** + * @brief Construct the pose using scalars for position and rotation angle. + * + * @param x,y : position (origin) of the target frame + * @param angle : initial heading angle (double is compatible)(radians). + */ + LegacyPose2D(const Float &x, const Float &y, const Angle &angle) : + rot( RotationMath::Rotation(angle)), + trans( (Translation() << x,y).finished() ) + {} + + /** + * @brief Construct the pose using a rotation matrix and a translation vector. + * + * This accepts arbitrary eigen types to use as a rotation matrix and + * translation vector. + * + * @param R : 2x2 rotation matrix. + * @param T : 2x1 translation vector (will compile error if incorrect size). + * @tparam Rot : any compatible eigen 2x2 matrix type (e.g. Matrix). + * @tparam Trans : any compatible eigen 2x1 matrix type (e.g. Matrix). + */ + template + LegacyPose2D(const ecl::linear_algebra::MatrixBase& R, const ecl::linear_algebra::MatrixBase& T) : + rot( RotationMath::Rotation(R) ), + trans(T) + {} + /** + * @brief Construct the pose using a rotational angle and a translation vector. + * + * This accepts an angle (or its Float equivalent) and an arbitrary eigen type + * to use as a translation vector. + * + * @param angle : initial heading angle (double is compatible)(radians). + * @param T : 2x1 translation vector (will compile error if incorrect size). + * @tparam Trans : any compatible eigen 2x1 matrix type (e.g. Matrix). + */ + template + LegacyPose2D(const Angle& angle, const ecl::linear_algebra::MatrixBase& T) : + rot( RotationMath::Rotation(angle) ), + trans(T) + {} + /** + * @brief Copy constructor that works for copies from any pose type. + * + * This works regardless of whatever storage the incoming pose is in. + * + * @param pose : the pose to copy. + */ + template + LegacyPose2D(const LegacyPose2D& pose) : + rot(RotationMath::Rotation(pose.rotation())), + trans(pose.translation()) + {} + + virtual ~LegacyPose2D() {} + + /****************************************** + ** Assignment + *******************************************/ + /** + * @brief Assign from another Pose2D instance. + * @param pose : another pose2D, storage type is irrelevant. + * @return Pose2D& : reference handle to this object. + */ + template + LegacyPose2D& operator=(const LegacyPose2D& pose) { + trans = pose.translation(); + rot = RotationMath::Rotation(pose.rotation()); + return *this; + } + + /****************************************** + ** Eigen Style Setters + *******************************************/ + /** + * @brief Set the rotational component with a heading angle. + * + * This accepts an input heading angle to configure the internal rotational + * storage. + * + * @param heading : configure the rotation from an input heading angle. + */ + void rotation(const Angle &heading) { + rot = RotationMath::Rotation(heading); + } + /** + * @brief Set the rotational component with a rotation matrix. + * + * This accepts an input rotation matrix to configure the internal rotational + * storage. + * + * @param rotation_matrix : input to copy across to the internal rotational storage. + */ + void rotation(const RotationMatrix &rotation_matrix) { + rot = RotationMath::Rotation(rotation_matrix); + } + /** + * @brief Set the translation vector from a pair of x,y values. + * + * This accepts x, y values to set the pose translation. + * + * @param x : x translation. + * @param y : y translation. + */ + void translation(const Float &x, const Float &y) { + this->trans << x, y; + } + /** + * @brief Set the translation vector. + * + * This accepts an arbitrary eigen types to use as a translation vector. Eigen + * will emit the appropriate compile time error if it is incompatible. + * + * @param T : 2x1 translation vector. + * @tparam Trans : any compatible eigen 2x1 matrix type (e.g. Matrix). + */ + template + void translation(const ecl::linear_algebra::MatrixBase& T) { + this->trans = T; + } + + /** + * @brief Set this pose to zero rotation and zero translation. + */ + void setIdentity() { + rot = RotationMath::Identity(); + trans << 0.0, 0.0; + } + + /** + * @brief Static function for returning the idenitity pose, eigen style. + * + * @return Pose2D : the zero rotation, zero translation pose. + */ + static LegacyPose2D Identity() { + return LegacyPose2D(); + } + + /****************************************** + ** Convenience Setters + *******************************************/ + void setPose(const Float& x, const Float& y, const Angle& heading) { trans << x,y; rot = RotationMath::Rotation(heading); } /**< @brief Sets the pose with a triplet. **/ + void x(const Float& value) { trans[0] = value; } //!< @brief Sets the x-coordinate. + void y(const Float& value) { trans[1] = value; } //!< @brief Sets the y-coordinate. + void heading(const Angle& value) { rot = RotationMath::Rotation(value); } //!< @brief Sets the heading. + + /** + * @brief Set the rotational component. + * + * This accepts arbitrary eigen types to use as a rotation matrix. Eigen + * will emit the appropriate compile time error if it is incompatible. + * + * @param rotation_matrix : 2x2 rotation matrix. + * @tparam Rot : any compatible eigen 2x2 matrix type (e.g. Matrix). + */ + template + void rotationMatrix(const ecl::linear_algebra::MatrixBase& rotation_matrix) { + rot = RotationMath::Rotation(rotation_matrix); + } + + /****************************************** + ** Eigen Style Accessors + *******************************************/ + RotationType& rotation() { return rot; } /**> @brief Return a mutable handle to the rotational storage component. **/ + Translation& translation() { return trans; } /**> @brief Return a mutable handle to the translation vector. **/ + const RotationType& rotation() const { return rot; } /**> @brief Return a const handle to the rotational storage component. **/ + const Translation& translation() const { return trans; } /**> @brief Return a const handle to the translation vector. **/ + + /****************************************** + ** Convenience Accessors + *******************************************/ + Float x() const { return trans[0]; } //!< @brief Get the x-coordinate. + Float y() const { return trans[1]; } //!< @brief Get the y-coordinate. + Angle heading() const { return RotationMath::Heading(rot); } //!< @brief Get the heading. + RotationMatrix rotationMatrix() const { return RotationMatrixMath::Rotation(rot); } /**< Representation of the rotation in matrix form. **/ + + /****************************************** + ** Operators + *******************************************/ + /** + * @brief Calculate the inverse pose. + * + * This calculates the reverse transformation between frames. + * + * @return Pose2D : the inverse pose with target and reference frames swapped. + */ + LegacyPose2D inverse() const { + LegacyPose2D inverse; + inverse.rotation(RotationMath::Inverse(rot)); + inverse.translation(-1*(RotationMatrixMath::Rotation(inverse.rot)*trans)); + return inverse; + } + + /** + * @brief Combine this pose with the incoming pose. + * @param pose : differential (wrt this pose's frame). + * @return Pose2D : new instance representing the product of the poses. + */ + template + LegacyPose2D operator*(const LegacyPose2D &pose) const { + return LegacyPose2D(RotationMath::Product(rot,pose.rot),trans + rotationMatrix()*pose.trans); + } + /** + * @brief Transform this pose by the specified input pose. + * @param pose : a pose differential (wrt this pose's frame). + * @return Pose2D& : handle to the updated pose (wrt common/global frame). + */ + LegacyPose2D& operator*=(const LegacyPose2D &pose) { + // This probably needs checking...could also be (marginally) sped up. + *this = (*this)*pose; + return (*this); + } + /** + * @brief Relative pose between this pose and another. + * + * Evaluates and returns the pose of this pose, relative to the specified pose. + * + * @code + * Pose2D a(1.0,1.0,1.57), b(1.0,2.0,3.14); + * Pose2D brela = b.relative(a); + * std::cout << brela << std::endl; // [1.0, 0.0, 1.57] + * @endcode + * + * @param pose : reference frame for the relative pose. + * @return Pose2D : new instance representing the relative. + */ + template + LegacyPose2D relative(const LegacyPose2D &pose) const { + return pose.inverse()*(*this); + } + + /********************* + ** Streaming + **********************/ + template + friend OutputStream& operator<<(OutputStream &ostream , const LegacyPose2D &pose); + +private: + RotationType rot; + Translation trans; +}; + +} // namespace ecl + +/***************************************************************************** +** Insertion Operators +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Insertion operator for output streams. + * + * Note that the output heading angle is formatted in degrees. + * + * @param ostream : stream satisfying the ecl stream concept. + * @param pose : the inserted pose. + * @return OutputStream : the returning stream handle. + */ +template +OutputStream& operator<<(OutputStream &ostream , const LegacyPose2D &pose) { + ecl::Format format; + format.width(6); + format.precision(3); + ostream << "[ "; + ostream << format(pose.x()) << " "; + ostream << format(pose.y()) << " "; + ostream << format(pose.heading()); + ostream << " ]"; + ostream.flush(); + return ostream; +} + + +} // namespace ecl + +// This is more convenient and less bughuntish than always assigning allocators with your vectors +// but currently fails on oneiric with gcc 4.6 (bugfixed in eigen, but not yet out in oneiric). +// EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose2D) +// EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose2D) +// EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose2D) +// EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose2D) + +#endif /* ECL_GEOMETRY_LEGACY_POSE2D_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose3d.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose3d.hpp new file mode 100644 index 0000000..6a1851f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/legacy_pose3d.hpp @@ -0,0 +1,334 @@ +/** + * @file /ecl_geometry/include/ecl/geometry/pose2d.hpp + * + * @brief Pose representations. + * + * These are particularly suited for mobile robot representaitons. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_LEGACY_POSE3D_HPP_ +#define ECL_GEOMETRY_LEGACY_POSE3D_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +#include + +#include "legacy_pose2d.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Pose3D] +*****************************************************************************/ + +/** + * @brief Parent template definition for Pose3D. + * + * Do not use this directly. Use the specialisations instead. + */ +template +class ECL_LOCAL LegacyPose3D { +private: + LegacyPose3D() {}; /**< @brief Prevents usage of this template class directly. **/ +}; + +/** + * @brief Representation for a 3D pose (6 degrees of freedom). + * + * This represents a transformation typical of that of an object in 3D, + * that is, it has 3 translational degrees of freedom and 3 rotational + * degrees of freedom. Default storage type for + * rotations is the rotation matrix. We may think about a quaternion + * storage type in the future. + * + * @tparam Float : must be a float type (e.g. float, double, float32, float64) + */ +template +class ECL_PUBLIC LegacyPose3D >::type> { +public: + /****************************************** + ** Eigen Alignment + *******************************************/ + EIGEN_MAKE_ALIGNED_OPERATOR_NEW // http://eigen.tuxfamily.org/dox/StructHavingEigenMembers.html + + /****************************************** + ** Typedef + *******************************************/ + typedef Float Scalar; /**< @brief Eigen style declaration of the element type. **/ + typedef ecl::linear_algebra::Matrix RotationMatrix; /**< @brief The type used to represent rotation matrices. **/ + typedef ecl::linear_algebra::Matrix Translation; /**< @brief The type used to represent translations. **/ + + /****************************************** + ** Constructors + *******************************************/ + /** + * @brief Initialise with zero rotation and zero translation. + */ + LegacyPose3D() : rot(RotationMatrix::Identity()), trans(Translation::Zero()) {} + + /** + * @brief Initialise with rotation matrix and translation. + * + * This accepts arbitrary eigen types to use as a rotation matrix and + * translation vector. + * + * @param rotation : 3x3 rotation matrix. + * @param translation : 3x1 translation vector (will compile error if incorrect size). + * @tparam Rot : any compatible eigen 3x3 matrix type (e.g. Matrix). + * @tparam Trans : any compatible eigen 3x1 matrix type (e.g. Matrix). + */ + template +// LegacyPose3D(const ecl::linear_algebra::MatrixBase& rotation, const ecl::linear_algebra::MatrixBase& translation) : + LegacyPose3D(const ecl::linear_algebra::EigenBase& rotation, const ecl::linear_algebra::EigenBase& translation) : + rot(rotation), + trans(translation) + {} + + /** + * @brief Initialise from a 2D pose. + * + * Essentially converts the 2D pose to a 3D pose, note that any 2D pose object will do. + * @param pose : the 2d pose. + */ + template + LegacyPose3D(const LegacyPose2D& pose) : + rot(RotationMatrix::Identity()), + trans(Translation::Zero()) + { + rot.template block<2,2>(0,0) = pose.rotationMatrix(); + trans.template segment<2>(0) = pose.translation(); + } + + /** + * @brief Initialise from an eigen AngleAxis and a translation. + * + * @param angle_axis : a 3d vector and scalar angle object from eigen. + * @param translation : 3x1 translation vector (will compile error if incorrect size). + * @tparam Trans : any compatible eigen 3x1 matrix type (e.g. Matrix). + */ + template + LegacyPose3D(const ecl::linear_algebra::AngleAxis& angle_axis, const ecl::linear_algebra::MatrixBase& translation) : + rot(RotationMatrix::Identity()), + trans(Translation::Zero()) + { + (void) angle_axis; + (void) translation; + /* TODO */ + } + /** + * @brief Initialise from an eigen Quaternion and a translation. + * + * @param quaternion : an eigen quaternion object. + * @param translation : 3x1 translation vector (will compile error if incorrect size). + * @tparam Trans : any compatible eigen 3x1 matrix type (e.g. Matrix). + */ + template + LegacyPose3D(const ecl::linear_algebra::Quaternion& quaternion, const ecl::linear_algebra::MatrixBase& translation) : + rot(quaternion.toRotationMatrix()), + trans(translation) + {} + + /** + * @brief Copy constructor for 3d poses. + * @param pose : the pose to be copied. + */ + LegacyPose3D(const LegacyPose3D& pose) : + rot(pose.rotation()), + trans(pose.translation()) + {} + + virtual ~LegacyPose3D() {} + + /****************************************** + ** Assignment + *******************************************/ + /** + * @brief Assign from another Pose2D instance. + * @param pose : another Pose2D, storage type is irrelevant. + * @return Pose2D& : reference handle to this object. + */ + template + LegacyPose3D& operator=(const LegacyPose2D& pose) { + rot.template block<2,2>(0,0) = pose.rotationMatrix(); + (rot.template block<2,1>(0,2)) << 0.0, 0.0; + (rot.template block<1,3>(2,0)) << 0.0, 0.0, 1.0; + trans.template segment<2>(0) = pose.translation(); + trans[2] = 0.0; + return *this; + } + + /** + * @brief Assign from another Pose2D instance. + * @param pose : another Pose2D, storage type is irrelevant. + * @return Pose2D& : reference handle to this object. + */ + LegacyPose3D& operator=(const LegacyPose3D& pose) { + rot = pose.rotation(); + trans = pose.translation(); + return *this; + } + /****************************************** + ** Eigen Style Setters + *******************************************/ + /** + * @brief Set the rotational component. + * + * This accepts a rotation matrix to set the rotational part of the pose. + * + * @param rotation : input rotation to set. + */ + void rotation(const RotationMatrix &rotation) { + rot = rotation; + } + /** + * @brief Set the translation vector. + * + * This accepts an arbitrary eigen types to use as a translation vector. Eigen + * will emit the appropriate compile time error if it is incompatible. + * + * @param translation : 3x1 translation vector. + * @tparam Trans : any compatible eigen 3x1 matrix type (e.g. Matrix). + */ + template + void translation(const ecl::linear_algebra::MatrixBase& translation) { + this->trans = translation; + } + /****************************************** + ** Convenience Setters + *******************************************/ + // set from EigenBase (aka affine transforms) + // set from Quaternions + // set from AngleAxis + + /****************************************** + ** Eigen Style Accessors + *******************************************/ + RotationMatrix& rotation() { return rot; } /**> @brief Return a mutable handle to the rotational storage component. **/ + Translation& translation() { return trans; } /**> @brief Return a mutable handle to the translation vector. **/ + const RotationMatrix& rotation() const { return rot; } /**> @brief Return a const handle to the rotational storage component. **/ + const Translation& translation() const { return trans; } /**> @brief Return a const handle to the translation vector. **/ + + /****************************************** + ** Convenience Accessors + *******************************************/ + // get a Quaternion for the rotation part + // get an AngleAxis for the rotation part + // get an Affine Transform (4x4) for the big lebowski + RotationMatrix rotationMatrix() const { return rot; } /**< @brief Representation of the rotation in matrix form. **/ + + /****************************************** + ** Operators + *******************************************/ + /** + * @brief Calculate the inverse pose. + * + * This calculates the reverse transformation between frames. + * + * @return Pose3D : the inverse pose with target and reference frames swapped. + */ + LegacyPose3D inverse() const { + LegacyPose3D inverse; + inverse.rotation(rot.transpose()); + inverse.translation(-1*(inverse.rot*trans)); + return inverse; + } + /** + * @brief Combine this pose with the incoming pose. + * @param pose : differential (wrt this pose's frame). + * @return Pose3D : new instance representing the product of the poses. + */ + template + LegacyPose3D operator*(const LegacyPose3D &pose) const { + return LegacyPose3D(rotation()*pose.rotation(),translation() + rotation()*pose.translation()); + } + + // Do we need operator* for Pose2D rh values? + // Probably better if we code like pose_3d*Pose3D(pose_2d) to avoid vague ambiguities. + + /** + * @brief Transform this pose by the specified input pose. + * @param pose : a pose differential (wrt this pose's frame). + * @return Pose3D& : handle to the updated pose (wrt common/global frame). + */ + template + LegacyPose3D& operator*=(const LegacyPose3D &pose) { + // This probably needs checking for aliasing...could also be (marginally) sped up. + *this = (*this)*pose; + return (*this); + } + /** + * @brief Relative pose between this pose and another. + * + * Evaluates and returns the pose of this pose, relative to the specified pose. + * + * @param pose : reference frame for the relative pose. + * @return Pose3D : new instance representing the relative. + */ + template + LegacyPose3D relative(const LegacyPose3D &pose) const { + return pose.inverse()*(*this); + } + + // how to do pose2d*pose3d without circular header? -> EigenBase? -> External operators? + + /********************* + ** Streaming + **********************/ + template + friend OutputStream& operator<<(OutputStream &ostream , const LegacyPose3D &pose); + +private: + RotationMatrix rot; + Translation trans; +}; + +/***************************************************************************** +** Insertion Operators +*****************************************************************************/ +/** + * @brief Insertion operator for output streams. + * + * Note that the output heading angle is formatted in degrees. + * + * @param ostream : stream satisfying the ecl stream concept. + * @param pose : the inserted pose. + * @return OutputStream : the returning stream handle. + */ +template +OutputStream& operator<<(OutputStream &ostream , const LegacyPose3D &pose) { + ecl::Format format; + format.width(6); + format.precision(3); + for ( unsigned int i = 0; i < 3; ++i ) { + ostream << "[ "; + for ( unsigned int j = 0; j < 3; ++j ) { + ostream << format(pose.rot(i,j)) << " "; + } + ostream << "] [ "; + ostream << format(pose.trans(i)) << " ]\n"; + } + ostream.flush(); + return ostream; +} + +} // namespace ecl + +// This is more convenient and less bughuntish than always assigning allocators with your vectors +// but currently fails on oneiric with gcc 4.6 (bugfixed in eigen, but not yet out in oneiric). +//EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose3D) +//EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(ecl::LegacyPose3D) + +#endif /* ECL_GEOMETRY_LEGACY_POSE3D_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/linear_segment.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/linear_segment.hpp new file mode 100644 index 0000000..7407173 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/linear_segment.hpp @@ -0,0 +1,62 @@ +/** + * @file /ecl_geometry/include/ecl/geometry/linear_segment.hpp + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_geometry_GEOMETRY_LINEAR_SEGMENT_HPP_ +#define ecl_geometry_GEOMETRY_LINEAR_SEGMENT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +class LinearSegment { +public: + LinearSegment(const double& x_1, + const double& y_1, + const double& x_2, + const double& y_2); + + /** + * @brief Distance of a point from the segment. + * + * Returns the distance from one of the end points if it is closer than + * the segment itself. + * + * TODO shift this to a standard geometry function + * computing the squared distance between two geometric objects. + * + * @param x : x coordinate of the point + * @param y : y-coordinate of the point + * @return double + */ + double squaredDistanceFromPoint(const double& x, const double& y) const; + + ecl::Parameter A, B, C; + +private: + double x_1, y_1; + double x_2, y_2; +}; + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace ecl + +#endif /* ecl_geometry_GEOMETRY_LINEAR_SEGMENT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/macros.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/macros.hpp new file mode 100644 index 0000000..c0e61aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/geometry/macros.hpp + * + * @brief Macros for ecl geometry. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_MACROS_HPP_ +#define ECL_GEOMETRY_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_geometry_EXPORTS // we are building a shared lib/dll + #define ecl_geometry_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_geometry_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_geometry_LOCAL ECL_HELPER_LOCAL +#else // ecl is being built around static libraries + #define ecl_geometry_PUBLIC + #define ecl_geometry_LOCAL +#endif + +#endif /* ECL_GEOMETRY_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry.hpp new file mode 100644 index 0000000..dfe32e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry.hpp @@ -0,0 +1,18 @@ +/** + * @file /include/ecl/geometry/odometry_helper.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ODOMETRY_ODOMETRY_HPP_ +#define ECL_ODOMETRY_ODOMETRY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "odometry_typedefs.hpp" +#include "odometry_helper.hpp" + +#endif /*ECL_ODOMETRY_ODOMETRY_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_helper.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_helper.hpp new file mode 100644 index 0000000..bdb6ec6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_helper.hpp @@ -0,0 +1,167 @@ +/** + * @file /include/ecl/geometry/odometry_helper.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ODOMETRY_ODOMETRY_HELPER_HPP_ +#define ECL_ODOMETRY_ODOMETRY_HELPER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "macros.hpp" +#include "odometry_typedefs.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace odometry { + +/***************************************************************************** +** Methods +*****************************************************************************/ + +/** @brief Shortest distance between a pose and a trajectory + * + * This uses straight lines between the trajectory poses + * to calculate the distance to the pose + */ +ecl_geometry_PUBLIC double distance(const Pose2D& pose, const Trajectory2D& trajectory); +/** @brief Shortest distance between a position and a trajectory + * + * This uses straight lines between the trajectory poses + * to calculate the distance to the pose + */ +ecl_geometry_PUBLIC double distance(const Position2D& position, const Trajectory2D& trajectory); + +ecl_geometry_PUBLIC bool empty(const Trajectory2D& trajectory); /**< @brief Check if trajectory ptr is empty (ptr not set or has no poses) */ +ecl_geometry_PUBLIC bool empty(const Odom2DTrajectory& trajectory); /**< @brief Check if trajectory ptr is empty (ptr not set or has no odometries) */ + +ecl_geometry_PUBLIC int size(const Trajectory2D& trajectory); /**< @brief Get the size of the trajectory */ +ecl_geometry_PUBLIC int size(const Odom2DTrajectory& trajectory); /**< @brief Get the size of the trajectory */ + +ecl_geometry_PUBLIC double distance(const Odom2D& a, const Odom2D& b); /**< @brief Distance between the positions of odometries */ +ecl_geometry_PUBLIC double distance(const Pose2D& a, const Pose2D& b); /**< @brief Distance between poses */ +ecl_geometry_PUBLIC double distance(const Pose2D& a, const Odom2D& b); /**< @brief Distance between a pose and the position of a odometry */ +ecl_geometry_PUBLIC double distanceSqared(const Odom2D& a, const Odom2D& b); /**< @brief Squared distance between the positions of odometries */ +ecl_geometry_PUBLIC double distanceSqared(const Pose2D& a, const Pose2D& b); /**< @brief Squared distance between poses */ + +/**< @brief Concat two trajectories + * + * Adds a trajectory to the end of another trajectory. + * Shouldn't be used for frequent adding because of bad performance. + */ +ecl_geometry_PUBLIC void addAtEnd(Trajectory2D& target, const Trajectory2D& addition); +/**< @brief Concat two odometry trajectories + * + * Adds a trajectory to the end of another trajectory. + * Shouldn't be used for frequent adding because of bad performance. + */ +ecl_geometry_PUBLIC void addAtEnd(Odom2DTrajectory& target, const Odom2DTrajectory& addition); + +ecl_geometry_PUBLIC Trajectory2D vectorToTrajectory(const std::vector& vec); /**< @brief Convert vector of Pose2D to Trajectory2D */ +ecl_geometry_PUBLIC Odom2DTrajectory vectorToTrajectory(const std::vector& vec); /**< @brief Convert vector of Odom2D to Odom2DTrajectory */ + +/**< @brief Resizes trajectory appending uninitialised values if needed + * + * This is conservative, meaning elements in the trajectory don't change. + * (Opposed to the default Eigen resize) + */ +ecl_geometry_PUBLIC void resize(Trajectory2D& trajectory, const int& size); +/**< @brief Resizes trajectory appending uninitialised values if needed + * + * This is conservative, meaning elements in the trajectory don't change. + * (Opposed to the default Eigen resize) + */ +ecl_geometry_PUBLIC void resize(Odom2DTrajectory& trajectory, const int& size); + +ecl_geometry_PUBLIC void setAt(Trajectory2D& trajectory, const int& index, const Pose2D& pose); /**< @brief Set element at index of trajectory */ +ecl_geometry_PUBLIC void setAt(Odom2DTrajectory& trajectory, const int& index, const Odom2D& odom); /**< @brief Set element at index of trajectory */ + +ecl_geometry_PUBLIC Pose2D getAt(const Trajectory2D& trajectory, const int& index); /**< @brief Get element of trajectory */ +ecl_geometry_PUBLIC Odom2D getAt(const Odom2DTrajectory& trajectory, const int& index); /**< @brief Get element of trajectory */ + +ecl_geometry_PUBLIC Pose2D getFront(const Trajectory2D& trajectory); /**< @brief Get front (first) element of trajectory */ +ecl_geometry_PUBLIC Pose2D getBack(const Trajectory2D& trajectory); /**< @brief Get back (last) element of trajectory */ +ecl_geometry_PUBLIC Odom2D getFront(const Odom2DTrajectory& trajectory); /**< @brief Get front (first) element of trajectory */ +ecl_geometry_PUBLIC Odom2D getBack(const Odom2DTrajectory& trajectory); /**< @brief Get back (last) element of trajectory */ + +ecl_geometry_PUBLIC Trajectory2D getPoses(const Odom2DTrajectory& trajectory); /**< @brief Extract poses of odom trajectory */ +ecl_geometry_PUBLIC Twist2DVector getTwists(const Odom2DTrajectory& trajectory); /**< @brief Extract twists of odom trajectory */ + +ecl_geometry_PUBLIC void setVelocityX(Odom2D& odom, const float& value); /**< @brief Set linear velocity x direction */ +ecl_geometry_PUBLIC void setVelocityY(Odom2D& odom, const float& value); /**< @brief Set linear velocity y direction */ +ecl_geometry_PUBLIC void setVelocityAngular(Odom2D& odom, const float& value); /**< @brief Set angular velocity */ + +ecl_geometry_PUBLIC void setVelocityX(Twist2D& twist, const float& value); /**< @brief Set linear velocity x direction */ +ecl_geometry_PUBLIC void setVelocityY(Twist2D& twist, const float& value); /**< @brief Set linear velocity y direction */ +ecl_geometry_PUBLIC void setVelocityAngular(Twist2D& twist, const float& value); /**< @brief Set angular velocity */ + +ecl_geometry_PUBLIC void setX(Odom2D& odom, const float& value); /**< @brief Set x position */ +ecl_geometry_PUBLIC void setY(Odom2D& odom, const float& value); /**< @brief Set y position */ +ecl_geometry_PUBLIC void setYaw(Odom2D& odom, const float& value); /**< @brief Set yaw (heading) */ + +ecl_geometry_PUBLIC void setX(Pose2D& pose, const float& value); /**< @brief Set x position */ +ecl_geometry_PUBLIC void setY(Pose2D& pose, const float& value); /**< @brief Set y position */ +ecl_geometry_PUBLIC void setYaw(Pose2D& pose, const float& value); /**< @brief Set yaw (heading) */ + +ecl_geometry_PUBLIC void setX(Position2D& position, const float& value); /**< @brief Set x position */ +ecl_geometry_PUBLIC void setY(Position2D& position, const float& value); /**< @brief Set y position */ + +ecl_geometry_PUBLIC float getVelocityX(const Odom2D& odom); /**< @brief Get linear velocity x direction */ +ecl_geometry_PUBLIC float getVelocityY(const Odom2D& odom); /**< @brief Get linear velocity y direction */ +ecl_geometry_PUBLIC float getVelocityAngular(const Odom2D& odom); /**< @brief Get angular velocity */ + +ecl_geometry_PUBLIC float getVelocityX(const Twist2D& twist); /**< @brief Get linear velocity x direction */ +ecl_geometry_PUBLIC float getVelocityY(const Twist2D& twist); /**< @brief Get linear velocity y direction */ +ecl_geometry_PUBLIC float getVelocityAngular(const Twist2D& twist); /**< @brief Get angular velocity */ + +ecl_geometry_PUBLIC float getX(const Odom2D& odom); /**< @brief Get x position */ +ecl_geometry_PUBLIC float getY(const Odom2D& odom); /**< @brief Get y position */ +ecl_geometry_PUBLIC float getYaw(const Odom2D& odom); /**< @brief Get yaw (heading) */ + +ecl_geometry_PUBLIC Pose2D getPose(const Odom2D& odom); /**< @brief Extract pose from odometry */ +ecl_geometry_PUBLIC Position2D getPosition(const Odom2D& odom); /**< @brief Extract position from odometry */ +ecl_geometry_PUBLIC Twist2D getTwist(const Odom2D& odom); /**< @brief Extract twist from odometry */ + +ecl_geometry_PUBLIC float getX(const Pose2D& pose); /**< @brief Get x position */ +ecl_geometry_PUBLIC float getY(const Pose2D& pose); /**< @brief Get y position */ +ecl_geometry_PUBLIC float getYaw(const Pose2D& pose); /**< @brief Get yaw (heading) */ + +ecl_geometry_PUBLIC Position2D getPosition(const Pose2D& pose); /**< @brief Extract position from pose */ + +ecl_geometry_PUBLIC float getX(const Position2D& position); /**< @brief Get x position */ +ecl_geometry_PUBLIC float getY(const Position2D& position); /**< @brief Get y position */ + +/***************************************************************************** +** C++11 helpers +*****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + + ecl_geometry_PUBLIC bool empty(const Trajectory2DPtr& trajectory_ptr); /**< @brief Check if trajectory ptr is empty (ptr not set or has no poses) */ + ecl_geometry_PUBLIC bool empty(const Odom2DTrajectoryPtr& trajectory_ptr); /**< @brief Check if trajectory ptr is empty (ptr not set or has no odometries) */ + + ecl_geometry_PUBLIC int size(const Trajectory2DPtr& trajectory); /**< @brief Get the size of the trajectory */ + ecl_geometry_PUBLIC int size(const Odom2DTrajectoryPtr& trajectory); /**< @brief Get the size of the trajectory */ + + ecl_geometry_PUBLIC Trajectory2DPtr vectorToTrajectoryPtr(const std::vector& vec); /**< @brief Convert vector of Pose2D to Trajectory2DPtr */ + ecl_geometry_PUBLIC Odom2DTrajectoryPtr vectorToTrajectoryPtr(const std::vector& vec); /**< @brief Convert vector of Odom2D to Odom2DTrajectoryPtr */ + +#endif /*ECL_CXX11_FOUND*/ + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace odometry +} // namsepace ecl + +#endif /*ECL_ODOMETRY_ODOMETRY_HELPER_HPP_*/ + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_typedefs.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_typedefs.hpp new file mode 100644 index 0000000..2564852 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/odometry_typedefs.hpp @@ -0,0 +1,139 @@ +/** + * @file /include/ecl/geometry/odometry_typedefs.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ODOMETRY_ODOMETRY_TYPEDEFS_HPP_ +#define ECL_ODOMETRY_ODOMETRY_TYPEDEFS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +#if defined(ECL_CXX11_FOUND) + #include +#endif + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace odometry { + +/***************************************************************************** +** Methods +*****************************************************************************/ + +/** + * @brief Float representation for a 2D position (x-, y-position). + * + * Represents a point in 2D. Uses a 2x1 Eigen vector. + */ +typedef Eigen::Vector2f Position2D; + +/** + * @brief Float representation of a path in 2D (x1,y1; x2,y2; ..; xn,yn). + * + * Represents a path in 2D of 2D points (no heading / orientation. + * Uses a 2xn Eigen matrix where each colum is one point of the path. + */ +typedef Eigen::Matrix2Xf Path2D; + +/** + * @brief Float representation of a pose in 2D (x, y, heading). + * + * Represents a pose in 2D (2D position + heading). + * Uses a 3x1 Eigen vector. + */ +typedef Eigen::Vector3f Pose2D; + +/** + * @brief Float representation of a trajectory in 2D (poses in 2D). + * + * Represents a trajectory in 2D of 2D poses (x, y, heading). + * Uses a 3xn Eigen matrix where each column is one pose of the trajectory. + */ +typedef Eigen::Matrix3Xf Trajectory2D; + +/** + * @brief Float representation of velocities in 2D (v_x, v_y, w). + * + * Represents a twist in 2D with the linear velocities in x- and y-direction + * (v_x, v_y) and the angular velocity (w). + * Uses a 3x1 Eigen vector. + */ +typedef Eigen::Vector3f Twist2D; + +/** + * @brief Float collection of 2D twists (twist: v_x, v_y, w). + * + * Represents a collection of linear and angular velocities in 2D (=twists). + * Uses a 3xn Eigen matrix where each column is one twist. + */ +typedef Eigen::Matrix3Xf Twist2DVector; + +/** + * @brief Float representation of 2D odometry (x, y, heading, v_x, v_y, w). + * + * Represents a pose (x, y, heading) and the twist (linear velocities, + * angular velocities) of an object in a 2D plane, e.g. a mobile robot. + * + * Uses a 6x1 Eigen vector where the upper half is the pose and the + * lower half the twist. + */ +typedef Eigen::Matrix Odom2D; + +/** + * @brief Float collection of 2D odometries (x, y, heading, v_x, v_y, w). + * + * Represents a collection of poses (x, y, heading) together with + * linear and angular velocities in 2D (=twists). + * + * Uses a 6xn Eigen matrix where each column is one odometry with + * the upper half being the pose and the lower half the twist. + */ +typedef Eigen::Matrix Odom2DTrajectory; + + +/***************************************************************************** +** c++11 shared_ptr typedefs +*****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + + /** @brief std::shared_ptr of Position2D (2x1 Eigen vector) */ + typedef std::shared_ptr Position2DPtr; + /** @brief std::shared_ptr of Path2D (2xn Eigen matrix) */ + typedef std::shared_ptr Path2DPtr; + + /** @brief std::shared_ptr of Pose2D (3x1 Eigen vector: x, y, heading) */ + typedef std::shared_ptr Pose2DPtr; + /** @brief std::shared_ptr of Trajectory2D (3xn Eigen matrix) */ + typedef std::shared_ptr Trajectory2DPtr; + + /** @brief std::shared_ptr of Twist2D (3x1 Eigen vector: v_x, v_y, w) */ + typedef std::shared_ptr Twist2DPtr; + /** @brief std::shared_ptr of Twist2DVector (3xn Eigen matrix) */ + typedef std::shared_ptr Twist2DVectorPtr; + + /** @brief std::shared_ptr of Odom2D (6xn Eigen vector) */ + typedef std::shared_ptr Odom2DPtr; + /** @brief std::shared_ptr of Odom2DTrajectory (6xn Eigen matrix) */ + typedef std::shared_ptr Odom2DTrajectoryPtr; + +#endif /*ECL_CXX11_FOUND*/ + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace odometry +} // namespace ecl + +#endif /*ECL_ODOMETRY_ODOMETRY_TYPEDEFS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pascals_triangle.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pascals_triangle.hpp new file mode 100644 index 0000000..8aa84c9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pascals_triangle.hpp @@ -0,0 +1,343 @@ +/** + * @file /include/ecl/geometry/pascals_triangle.hpp + * + * @brief Templatised specialisations for pascal's triangle. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_PASCALS_HPP_ +#define ECL_GEOMETRY_PASCALS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Class [PascalsTriangle] +*****************************************************************************/ + +/** + * @brief Holds the coefficients for pascal's triangle up to row N. + * + * Stores the coefficients of all rows (determined in diagonal order) + * up until row N - i.e. all coefficients up to and including those + * for (x+y)^0 to (x+y)^N. Coefficients are stored as a sequence of + * rows going from top to bottom right (of the triangle) + * and moving left. For example, for N = 5, the representation + * in the array is as shown below: + * @code + * (*this) = 1,1,1,1,1,1, + * 1,2,3,4,5, + * 1,3,6,10, + * 1,4,10, + * 1,5, + * 1; + * @endcode + * + * @tparam N : calculate the triangle to the N-th power. + * + * @sa @ref polynomialsGeometry "Math::Polynomials". + */ +template +class ECL_PUBLIC PascalsTriangle { + public: + /********************* + ** C&D + **********************/ + PascalsTriangle(); + virtual ~PascalsTriangle() {}; + + /********************* + ** Iterators + **********************/ + typedef typename Array::const_iterator const_iterator; /**< @brief Utilise the array's iterator for parsing the triangle. **/ + const_iterator begin(unsigned int index = 0) const; + const_iterator end(unsigned int index = 0) const; + + /********************* + ** Streaming + **********************/ + template + friend OutputStream& operator<<(OutputStream &ostream, const PascalsTriangle &triangle); + + private: + Array coefficients; +}; +/***************************************************************************** +** Specialisations [Pascals Triangle][3] +*****************************************************************************/ +/** + * @brief Holds the coefficients of pascal's triangle up to n = 3. + * + * Stores the coefficients of all diagonals up until row 3 - i.e. + * all coefficients up to and including those for (x+y)^0 to (x+y)^3. + * This is used fairly often, so defined here to avoid the slow + * calculation of the general case. + * + * @sa @ref PascalsTriangle, @ref polynomialsGeometry "Math::Polynomials". + */ +template <> +class ECL_PUBLIC PascalsTriangle<3> { + public: + /********************* + ** C&D + **********************/ + /** + * @brief Default constructor. + * + * This constructor speeds things up + * by initialising the triangle internally with the coefficients directly. + */ + PascalsTriangle(); + virtual ~PascalsTriangle() {}; + + /********************* + ** Iterators + **********************/ + typedef Array::const_iterator const_iterator; /**< @brief Utilise the array's iterator for parsing the triangle. **/ + /** + * @brief Iterator generator for diagonals of pascals triangle [begin]. + * + * Return a const iterator pointing to the first element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing pointing to the first element of the specified diagonal/row. + **/ + const_iterator begin(unsigned int index = 0) const; + /** + * @brief Iterator generator for diagonals of pascals triangle [begin]. + * + * Return a const iterator just past the last element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing just beyond the last of the specified diagonal/row. + **/ + const_iterator end(unsigned int index = 0) const; + + /********************* + ** Streaming + **********************/ + template + friend OutputStream& operator<<(OutputStream &ostream, const PascalsTriangle<3> &triangle); + + private: + Array coefficients; +}; + +/***************************************************************************** +** Specialisations [Pascals Triangle][5] +*****************************************************************************/ +/** + * @brief Holds the coefficients of pascal's triangle up to n = 5. + * + * Stores the coefficients of all diagonals up until row 5 - i.e. + * all coefficients up to and including those for (x+y)^0 to (x+y)^5. + * This is used fairly often, so defined here to avoid the slow + * calculation of the general case. + * + * @sa @ref PascalsTriangle, @ref polynomialsGeometry "Math::Polynomials". + */ +template <> +class ECL_PUBLIC PascalsTriangle<5> { + public: + /********************* + ** C&D + **********************/ + /** + * @brief Default constructor. + * + * This constructor speeds things up + * by initialising the triangle internally with the coefficients directly. + */ + PascalsTriangle(); + virtual ~PascalsTriangle() {}; + + /********************* + ** Iterators + **********************/ + typedef Array::const_iterator const_iterator; /**< @brief Utilise the array's iterator for parsing the triangle. **/ + /** + * @brief Iterator generator for diagonals of pascals triangle [begin]. + * + * Return a const iterator pointing to the first element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing pointing to the first element of the specified diagonal/row. + **/ + const_iterator begin(unsigned int index = 0) const; + /** + * @brief Iterator generator for diagonals of pascals triangle [begin]. + * + * Return a const iterator just past the last element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing just beyond the last of the specified diagonal/row. + **/ + const_iterator end(unsigned int index = 0) const; + + /********************* + ** Streaming + **********************/ + template + friend OutputStream& operator<<(OutputStream &ostream, const PascalsTriangle<5> &triangle); + + private: + Array coefficients; +}; + +/***************************************************************************** +** Implementation [Pascals Triangle] +*****************************************************************************/ +/** + * @brief Default constructor. + * + * This computes all coefficients of the triangle up to row N. + */ +template +PascalsTriangle::PascalsTriangle() { + int counter = 0; + for (int i = N+1; i > 0; --i ) { + for (int j = 0; j < i; ++j ) { + if ( ( i == N+1 ) || ( j == 0 ) ) { + coefficients[counter] = 1; + } else { + coefficients[counter] = coefficients[counter-1] + coefficients[counter-(i+1)]; + } + ++counter; + } + } +} + +/** + * @brief Iterator generator for diagonals of pascals triangle [begin]. + * + * Return a const iterator pointing to the first element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing pointing to the first element of the specified diagonal. + **/ +template +typename PascalsTriangle::const_iterator PascalsTriangle::begin(unsigned int index) const { + int coeff_index = 0; + for (unsigned int i = 0; i < index; ++i ) { + coeff_index += N+1-i; + } + return const_iterator( &coefficients[coeff_index] ); +} +/** + * @brief Iterator generator for diagonals of pascals triangle [end]. + * + * Return a const iterator just past the last element of the specified diagonal. + * @param index : the diagonal to be iterated. + * @return const_iterator : constant iterator pointing just beyond the last of the specified diagonal. + **/ +template +typename PascalsTriangle::const_iterator PascalsTriangle::end(unsigned int index) const { + int coeff_index = 0; + for (unsigned int i = 0; i <= index; ++i ) { + coeff_index += N+1-i; + } + coeff_index -= 1; // dont want to call beyond the array limit. + return const_iterator( (&coefficients[coeff_index])+1); +} + +/***************************************************************************** +** Streaming +*****************************************************************************/ + +/** + * @brief Streaming output insertion operator for for pascal triangles. + * + * Streaming output insertion operator for for pascal triangles. + * + * @tparam OutputStream : the type of stream being used. + * @tparam PowerN : the order of the pascal's triangle being inserted. + * + * @param ostream : the stream to send the output to. + * @param triangle : the pascal triangle object. + * @return OutputStream : the output stream. + */ +template +OutputStream& operator << ( OutputStream &ostream, const PascalsTriangle &triangle) +{ + Format format(2+PowerN/5,CentreAlign); // Rough hack to get a good auto-sizing working. Might blow up for large N. + int counter = 0; + for (int i = PowerN+1; i > 0; --i ) { + for (int j = 0; j < i; ++j ) { + ostream << format(triangle.coefficients[counter]) << " "; + ++counter; + } + ostream << "\n"; + } + ostream.flush(); + + return ostream; +} + +/** + * @brief Insertion operator for streaming output from pascal's triangle of degree 3. + * + * Insertion operator for streaming output from pascal's triangle. + * + * @param ostream : the stream to send the output to. + * @param triangle : the pascal triangle object. + * @return OutputStream : the output stream. + */ +template +OutputStream& operator << ( OutputStream &ostream, const PascalsTriangle<3> &triangle) +{ + Format format(2,CentreAlign); + int counter = 0; + for (int i = 4; i > 0; --i ) { + for (int j = 0; j < i; ++j ) { + ostream << format(triangle.coefficients[counter]) << " "; + ++counter; + } + ostream << "\n"; + } + ostream.flush(); + + return ostream; +} + +/** + * @brief Insertion operator for streaming output from pascal's triangle of degree 5. + * + * Insertion operator for streaming output from pascal's triangle. + * + * @param ostream : the output stream being used. + * @param triangle : the pascal triangle object. + * @return OutputStream : the output stream. + */ +template +OutputStream& operator << ( OutputStream &ostream, const PascalsTriangle<5> &triangle) +{ + Format format(3,CentreAlign); + int counter = 0; + for (int i = 6; i > 0; --i ) { + for (int j = 0; j < i; ++j ) { + ostream << format(triangle.coefficients[counter]) << " "; + ++counter; + } + ostream << "\n"; + } + ostream.flush(); + + return ostream; +} + +} // namespace ecl + + + +#endif /* ECL_GEOMETRY_PASCALS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/polynomial.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/polynomial.hpp new file mode 100644 index 0000000..7e77f6c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/polynomial.hpp @@ -0,0 +1,1352 @@ +/** + * @file /include/ecl/geometry/polynomial.hpp + * + * @brief Representations for polynomial functions. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_POLYNOMIALS_HPP_ +#define ECL_GEOMETRY_POLYNOMIALS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "cartesian_point.hpp" +#include "function_math.hpp" +#include "pascals_triangle.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward declarations +*****************************************************************************/ + +template class Polynomial; + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ + +/** + * @brief Primary template for the @ref ecl::Polynomial "Polynomial" blueprint factories. + * + * Primary template for the polynomial blueprint factories. This is in fact empty since it covers + * polynomials of all orders. Particular polynomial blueprint factories are specified in the + * specialisations. + * + * @tparam N : degree of the polynomials to create blueprints for. + * + * @sa @ref ecl::Polynomial "Polynomial", BluePrintFactory< ecl::Polynomial<3> >. + */ +template +class BluePrintFactory< Polynomial > { +public: + BluePrintFactory() {}; + ~BluePrintFactory() {}; +}; + +/***************************************************************************** +** Interface [Polynomial] +*****************************************************************************/ +/** + * @brief Representation of a polynomial function of n-th degree. + * + * Representation of a polynomial function of n-th order. Use the template + * parameter to specify the degree of the polynomial. The representation is + * defined by an array of coefficients which are given in the form + * a_0 -> a_n where p(x) = a_0 + a_1 x + .... + * + * Comma Initialisation: + * + * The polynomial uses a an ecl array (ecl_containers) for storage, + * so comma initialisation is possible. + * @code + * // Comma Initialisation + * Polynomial<5> p; + * p.coefficients() = 1,2,3,4,5,6; + * cout << p << endl; // 1.00 + 2.00x + 3.00x^2 + 4.00x^3 + 5.00x^4 + 6.00x^5 + * @endcode + * + * Blueprint Initialisation: + * + * Lightweight blueprints can also be used to initialise/assign the polynomial: + * + * @code + * CubicPolynomial cubic = CubicPolynomial::Interpolation(2.0,0.0,0.0,3.0,1.0,0.0); + * @endcode + * + * Utility Functions: + * + * - Maximum + * - Minimum + * - Maximum + * - Minimum + * + * @tparam N : the degree of the polynomial (i.e. a_0 + ... + a_i x^i + ... + a_N x^N) + * + * @sa @ref polynomialsGeometry "Math::Polynomials". + **/ +template +class ecl_geometry_PUBLIC Polynomial : public BluePrintFactory< Polynomial >, public FunctionMath< Polynomial > { + public: + /********************* + ** Convenience + **********************/ + typedef Array Coefficients; /**< @brief The coefficient container storage type. **/ + + /********************* + ** C&D + **********************/ + /** + * @brief Default constructor. + * + * This does not initialise the polynomial, use with the + * coefficients() accessor with comma initialisation operator to + * conveniently set the coefficients. + **/ + Polynomial() : coeff(Coefficients::Constant(0.0)) {}; + + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * CubicPolynomial cubic = CubicPolynomial::Interpolation(2.0,0.0,0.0,3.0,1.0,0.0); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * CubicPolynomial cubic; // Alternatively Polynomial<3> + * cubic = CubicPolynomial::Interpolation(2.0,0.0,0.0,3.0,1.0,0.0); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprints concept (refer to ecl_concepts' documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa ecl::BluePrintFactory, + * ecl::BluePrintFactory, + * ecl::BluePrintFactory. + */ + template + Polynomial(const BluePrint< Derived > &blueprint) { + blueprint.implementApply(*this); + } + virtual ~Polynomial() {} + + /********************* + ** Transform + **********************/ + /** + * @brief Horizontal shift transform. + * + * Shifts the polynomial along the x axis by the specified offset. + * A negative offset will shift the polynomial to the left, while + * a positive offset will shit the polynomial to the right. + * + * @code + * Polynomial<2> quadratic; // x^2 + * quadratic.shift(2); // x^2 -> (x-2)^2 (graph shifted right by 2) + * @endcode + * + * @param shift : the amount of x-shift (-ve -> left, +ve -> right). + **/ + void shift_horizontal(const double &shift); +// void stretch_horizontal(double multiplier); + + /********************* + ** Derivatives + **********************/ + /** + * @brief Generates the derivative polynomial. + * + * Calculates and returns a copy of the derivative polynomial. + * + * @return Polynomial : the derivative polynomial. + */ + Polynomial derivative() const { + Polynomial derivative_polynomial; + typename Polynomial::Coefficients &derivative_coefficients = derivative_polynomial.coefficients(); + for ( unsigned int i = 0; i < N; ++i ) { + derivative_coefficients[i] = (i+1)*coeff[i+1]; + } + return derivative_polynomial; + } + /** + * @brief Access the derivative directly. + * + * Access the values of the derivative directly. + * + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the derivative at x. + */ + double derivative(const double &x) const; + /** + * @brief Access the second derivative directly. + * + * Access the values of the second derivative directly. + * + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the second derivative at x. + */ + double dderivative(const double &x) const; + + /********************* + ** Accessors + **********************/ + /** + * @brief Handle to the coefficient array, use to initialise the polynomial. + * + * This returns a handle to the coefficient array. Use this with + * the comma initialiser to conveniently set the polynomial. + * + * @code + * Polynomial<5> p; + * p.coefficients() = 1,2,3,4,5,6; + * cout << p << endl; // 1.00 + 2.00x + 3.00x^2 + 4.00x^3 + 5.00x^4 + 6.00x^5 + * @endcode + * + * @return Coefficients& : reference to the co-efficient array. + **/ + Coefficients& coefficients() { return coeff; }; + /** + * @brief Non-modifiable handle to the coefficient array. + * + * @return const Coefficients& : non-modifiable reference to the co-efficient array. + **/ + const Coefficients& coefficients() const { return coeff; }; + + /** + * @brief Access the value of the polynomial at a certain point. + * + * Access the value of the polynomial at a certain point. + * + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the polynomial at x. + **/ + double operator ()(const double &x) const; + + /** + * @brief Streaming output insertion operator for polynomials. + * + * Streaming output insertion operator for polynomials. + * + * @tparam OutputStream : the type of stream being used. + * @tparam Degree : the order of the polynomial being inserted. + * + * @param ostream : the output stream being used. + * @param polynomial : the polynomial + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, const Polynomial &polynomial); + + private: + Coefficients coeff; +}; + +/** + * @brief Specialisation for the zero-th order polynomial. + * + * Represents a zero'th order polynomial (scalar). It is necessary to handle this + * separately as the derivatives do not return lower degree polynomials. + * + * @sa Polynomial, @ref polynomialsGeometry "Math::Polynomials". + **/ +template <> +class ECL_PUBLIC Polynomial<0> { + public: + /********************* + ** Convenience + **********************/ + typedef Array Coefficients; /**< @brief The coefficient container storage type. **/ + + /********************* + ** C&D + **********************/ + /** + * @brief Default constructor. + * + * This initialises the scalar coefficient for the zero'th polynomial + * to zero. + **/ + Polynomial() : coeff(Coefficients::Constant(0.0)) {}; + virtual ~Polynomial() {}; + + /********************* + ** Transform + **********************/ + /** + * @brief Horizontal shift transform. + * + * Normally, shifts the polynomial along the x axis by the specified offset, + * but in the case of this specialisation, does not change the polynomial. + **/ + void shift_horizontal(const double& /* shift */) {}; // Does nothing. + + /********************* + ** Derivatives + **********************/ + /** + * @brief Derivative of a zero'th order polynomial is always zero. + * + * Derivative of a zero'th order polynomial is always zero. + * + * @return Polynomial<0> : the zero polynomial. + */ + Polynomial<0> derivative() const { + return Polynomial<0>(); + } + /** + * @brief Access the derivative directly (always returns 0). + * + * Access the values of the derivative directly (always returns 0).. + * + * @return double : derivative of a scalar is always 0.0. + */ + double derivative(const double& /* x */ ) const { + return 0.0; + }; + /** + * @brief Access the second derivative directly (always returns 0).. + * + * Access the values of the second derivative directly (always returns 0).. + * + * @return double : 2nd derivative of a scalar is always 0.0. + */ + double dderivative(const double& /* x */) const { + return 0.0; + }; + + /********************* + ** Accessors + **********************/ + /** + * @brief Handle to the coefficient array, use to initialise the polynomial. + * + * This returns a handle to the coefficient array. Use this with + * the comma initialiser to conveniently set the polynomial. + * + * @code + * Polynomial<0> p; + * p.coefficients() = 1; + * cout << p << endl; // 1.00 + * @endcode + * + * @return Coefficients& : reference to the co-efficient array. + **/ + Coefficients& coefficients() { return coeff; }; + /** + * @brief Non-modifiable handle to the coefficient array. + * + * @return const Coefficients& : non-modifiable reference to the co-efficient array. + **/ + const Coefficients& coefficients() const { return coeff; }; + + /** + * @brief Access the value of the polynomial at the specified point. + * + * Access the value of the polynomial at the specified point. + * + * @return double : the value of a scalar is always a_0. + **/ + double operator ()(const double& /* x */) const { + return coeff[0]; + }; + + private: + Coefficients coeff; +}; + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +typedef Polynomial<1> LinearFunction; /**< @brief Mathematical term for 1st order polynomials. **/ +typedef Polynomial<2> QuadraticPolynomial; /**< @brief Mathematical term for 2nd order polynomials. **/ +typedef Polynomial<3> CubicPolynomial; /**< @brief Mathematical term for 3rd order polynomials. **/ +typedef Polynomial<5> QuinticPolynomial; /**< @brief Mathematical term for 5th order polynomials. **/ + +/***************************************************************************** + * Implementation [Polynomial - Transform] + ****************************************************************************/ +template +void Polynomial::shift_horizontal(const double &shift) +{ + PascalsTriangle pascals_triangle; + typename PascalsTriangle::const_iterator iter; + double tmp; + + for ( unsigned int i = 0; i < N; ++i ) { + tmp = -1*shift; + int j = i+1; + for ( iter = (pascals_triangle.begin(i)+1); iter != pascals_triangle.end(i); ++iter ) { // skip the first one + coeff[i] += (*iter)*tmp*coeff[j]; + tmp *= (-1*shift); + ++j; + } + } +} +/***************************************************************************** + * Implementation [Polynomial - Access] + ****************************************************************************/ +template +double Polynomial::operator()(const double &x) const +{ + double tmp = x; + double value = coeff[0]; + for ( unsigned int i = 1; i <= N; ++i ) { + value += coeff[i]*tmp; + tmp *= x; + } + return value; +} +template +double Polynomial::derivative(const double &x) const { + + if ( N > 0 ) { + return derivative()(x); + } else { + return 0.0; + } +} + +template +double Polynomial::dderivative(const double &x) const { + + if ( N > 1 ) { + return derivative().derivative()(x); + } else { + return 0.0; + } +} + +/***************************************************************************** +** Streaming Operator [Polynomial] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, const Polynomial &polynomial) +{ + ecl_compile_time_concept_check(StreamConcept); + + Format format; + format.precision(2); + + ostream << format(polynomial.coeff[0]); + for (unsigned int i = 1; i <= Degree; ++i) { + ostream << " + " << format(polynomial.coeff[i]) << "x^" << i; + } + ostream.flush(); + + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [LinearInterpolation] +*****************************************************************************/ + +/** + * @brief Blueprint for interpolating a linear function connecting end point conditions. + * + * Blueprint for interpolating a linear function connecting two points. That is, + * the resulting linear function y(x) should satisfy the following conditions: + * + * @code + * y(x_i) = y_i + * y(x_f) = y_f + * @endcode + * + * @sa @ref ecl::LinearFunction. + * + **/ +class ecl_geometry_PUBLIC LinearInterpolation : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::LinearFunction base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the linear function. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + */ + LinearInterpolation(const double x_i, const double y_i, const double x_f, const double y_f) : + x_initial(x_i), + y_initial(y_i), + x_final(x_f), + y_final(y_f) + {} + + virtual ~LinearInterpolation() {} + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new linear function generated from the input boundary conditions. + * + * @return LinearFunction : a copy of the generated function. + */ + ecl::LinearFunction instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate coefficients for the given polynomial. + * @param function : the linear function to configure from the supplied boundary conditions. + */ + void apply(ecl::LinearFunction& function) const; + + private: + double x_initial, y_initial; + double x_final, y_final; +}; + +/***************************************************************************** +** Interface [LinearPointSlope] +*****************************************************************************/ +/** + * @brief Blueprint for generating a linear function from slope and point pair. + * + * That is, the resulting linear function y(x) should satisfy the following conditions: + * + * @code + * (y(x_f)-y(x)) = slope*(x_f-x) + * y(x_f) = y_f + * @endcode + * + * @sa @ref ecl::LinearFunction. + * + **/ +class ecl_geometry_PUBLIC LinearPointSlopeForm : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::LinearFunction base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the linear function. + * + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param s : slope + */ + LinearPointSlopeForm(const double x_f, const double y_f, const double s) : + slope(s), + x_final(x_f), + y_final(y_f) + {} + + virtual ~LinearPointSlopeForm() {} + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new linear function generated from the input conditions. + * + * @return LinearFunction : a copy of the generated function. + */ + ecl::LinearFunction instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate coefficients for the given polynomial. + * @param function : the linear function to configure from the input conditions. + */ + void apply(ecl::LinearFunction& function) const; + + private: + double slope; + double x_final, y_final; +}; + + +/***************************************************************************** +** Interface [CubicDerivativeInterpolation] +*****************************************************************************/ + +/** + * @brief Blueprint for interpolating a cubic polynomial between end point conditions. + * + * Blueprint for interpolating a cubic polynomial between two end point conditions. That is, + * the resulting polynomial y(x) should satisfy the following conditions: + * + * @code + * y(x_i) = y_i + * y(x_f) = y_f + * y'(x_i) = y'_i + * y'(x_f) = y'_f + * @endcode + * + * @sa @ref ecl::Polynomial "Polynomial". + * + **/ +class ecl_geometry_PUBLIC CubicDerivativeInterpolation : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::CubicPolynomial base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the cubic. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param ydot_i : initial polynomial slope. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param ydot_f : final polynomial slope. + */ + CubicDerivativeInterpolation(const double x_i, const double y_i, const double ydot_i, + const double x_f, const double y_f, const double ydot_f) : + x_initial(x_i), + y_initial(y_i), + ydot_initial(ydot_i), + x_final(x_f), + y_final(y_f), + ydot_final(ydot_f) + {} + + virtual ~CubicDerivativeInterpolation() {} + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new cubic generated from the input boundary conditions. + * + * @return CubicPolynomial : a copy of the generated cubic. + */ + ecl::CubicPolynomial instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate coefficients for the given polynomial. + * @param polynomial : the polynomial to configure from the supplied boundary conditions. + */ + void apply(ecl::CubicPolynomial& polynomial) const; + + private: + double x_initial, y_initial, ydot_initial; + double x_final, y_final, ydot_final; +}; +/***************************************************************************** +** Interface [CubicSecondDerivativeInterpolation] +*****************************************************************************/ + +/** + * @brief Blueprint for interpolating a cubic polynomial between end point conditions. + * + * Blueprint for interpolating a cubic polynomial between two end point conditions. That is, + * the resulting polynomial y(x) should satisfy the following conditions: + * + * @code + * y(x_i) = y_i + * y(x_f) = y_f + * y''(x_i) = y''_i + * y''(x_f) = y''_f + * @endcode + * + * @sa @ref ecl::Polynomial "Polynomial". + * + **/ +class ecl_geometry_PUBLIC CubicSecondDerivativeInterpolation : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::CubicPolynomial base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the cubic. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param yddot_i : initial polynomial curvature. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param yddot_f : final polynomial curvature. + */ + CubicSecondDerivativeInterpolation(const double x_i, const double y_i, const double yddot_i, + const double x_f, const double y_f, const double yddot_f) : + x_initial(x_i), + y_initial(y_i), + yddot_initial(yddot_i), + x_final(x_f), + y_final(y_f), + yddot_final(yddot_f) + {} + + virtual ~CubicSecondDerivativeInterpolation() {} + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new cubic generated from the input boundary conditions. + * + * @return CubicPolynomial : a copy of the generated cubic. + */ + base_type instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate coefficients for the given polynomial. + * @param polynomial : the polynomial to configure from the supplied boundary conditions. + */ + void apply(base_type& polynomial) const; + + private: + double x_initial, y_initial, yddot_initial; + double x_final, y_final, yddot_final; +}; + +/***************************************************************************** +** Interface [QuinticInterpolation] +*****************************************************************************/ + +/** + * @brief Blueprint for interpolating a quintic polynomial between end point conditions. + * + * Blueprint for interpolating a quintic polynomial between two end point conditions. That is, + * the resulting polynomial y(x) should satisfy the following conditions: + * + * @code + * y(x_i) = y_i + * y'(x_i) = y'_i + * y''(x_i) = y''_i + * y(x_f) = y_f + * y'(x_f) = y'_f + * y''(x_f) = y''_f + * @endcode + * + * @sa @ref ecl::Polynomial "Polynomial". + * + **/ +class ecl_geometry_PUBLIC QuinticInterpolation : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::QuinticPolynomial base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the cubic. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param ydot_i : initial polynomial slope. + * @param yddot_i : initial polynomial curvature. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param ydot_f : final polynomial slope. + * @param yddot_f : final polynomial curvature. + */ + QuinticInterpolation(const double x_i, const double y_i, const double ydot_i, const double yddot_i, + const double x_f, const double y_f, const double ydot_f, const double yddot_f) : + x_initial(x_i), + y_initial(y_i), + ydot_initial(ydot_i), + yddot_initial(yddot_i), + x_final(x_f), + y_final(y_f), + ydot_final(ydot_f), + yddot_final(yddot_f) + {} + + virtual ~QuinticInterpolation() {} + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new cubic generated from the input boundary conditions. + * + * @return QuinticPolynomial : a copy of the generated cubic. + */ + ecl::QuinticPolynomial instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate coefficients for the given polynomial. + * @param polynomial : the polynomial to configure from the supplied boundary conditions. + */ + void apply(ecl::QuinticPolynomial& polynomial) const; + + private: + double x_initial, y_initial, ydot_initial, yddot_initial; + double x_final, y_final, ydot_final, yddot_final; +}; + +} // namespace blueprints + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ + +using blueprints::LinearInterpolation; +using blueprints::LinearPointSlopeForm; +using blueprints::CubicDerivativeInterpolation; +using blueprints::CubicSecondDerivativeInterpolation; +using blueprints::QuinticInterpolation; + +/** + * @brief Blueprint factory for linear functions. + * + * Generates various blueprints that instantiate or configure linear functions with + * commonly used configurations. This class is inherited by the LinearFunction class, + * consequently it is simpler to access these blueprints via the inheritance mechanisms + * than to use this class directly. For example, + * + * @code + * LinearFunction function = LinearFunction::Interpolation(0.0,0.0,1.0,2.0); + * @endcode + * + * @sa @ref ecl::LinearFunction "LinearFunction". + */ +template<> +class BluePrintFactory< LinearFunction > { +public: + /** + * @brief Blueprint for an interpolating a linear function connecting two points. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * + * @return LinearInterpolation : the resulting blueprint. + * + * @sa ecl::blueprints::LinearInterpolation + */ + static LinearInterpolation Interpolation(const double x_i, const double y_i, const double x_f, const double y_f); + /** + * @brief Blueprint for an generating a linear function from slope/point form. + * + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param slope : slope of the linear function + * @return LinearPointSlopeForm : the resulting blueprint. + */ + static LinearPointSlopeForm PointSlopeForm(const double x_f, const double y_f, const double slope); + virtual ~BluePrintFactory() {} +}; + +/** + * @brief Blueprint factory for cubic polynomials. + * + * Generates various blueprints that instantiate or configure cubic polynomials with + * commonly used configurations. This class is inherited by the CubicPolynomial class, + * consequently it is simpler to access these blueprints via the inheritance mechanisms + * than to use this class directly. For example, + * + * @code + * CubicPolynomial cubic = CubicPolynomial::DerivativeInterpolation(0.0,0.0,0.0,1.0,2.0,0.0); + * CubicPolynomial cubic = CubicPolynomial::SecondDerivativeInterpolation(0.0,0.0,0.0,1.0,2.0,0.0); + * @endcode + * + * @sa @ref ecl::CubicPolynomial "CubicPolynomial". + */ +template<> +class BluePrintFactory< CubicPolynomial > { +public: + /** + * @brief Blueprint for an interpolating cubic between two end points using derivatives. + * + * Generates a blueprint for creating cubic polynomials generated from + * value and derivative constraints on the endpoints. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param ydot_i : initial polynomial slope. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param ydot_f : final polynomial slope. + * + * @return CubicDerivativeInterpolation : the resulting blueprint. + * + * @sa ecl::blueprints::CubicDerivativeInterpolation + */ + static CubicDerivativeInterpolation DerivativeInterpolation(const double x_i, const double y_i, const double ydot_i, + const double x_f, const double y_f, const double ydot_f); + + /** + * @brief Blueprint for an interpolating cubic between two end points using second derivatives. + * + * Generates a blueprint for creating cubic polynomials generated from + * value and second derivative constraints on the endpoints. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param yddot_i : initial polynomial curvature. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param yddot_f : final polynomial curvature. + * + * @return CubicSecondDerivativeInterpolation : the resulting blueprint. + * + * @sa ecl::blueprints::CubicSecondDerivativeInterpolation + */ + static CubicSecondDerivativeInterpolation SecondDerivativeInterpolation(const double x_i, const double y_i, const double yddot_i, + const double x_f, const double y_f, const double yddot_f); + + virtual ~BluePrintFactory() {} +}; + +/** + * @brief Blueprint factory for quintic polynomials. + * + * Generates various blueprints that instantiate or configure quintic polynomials with + * commonly used configurations. This class is inherited by the QuinticPolynomial class, + * consequently it is simpler to access these blueprints via the inheritance mechanisms + * than to use this class directly. For example, + * + * @code + * QuinticPolynomial quintic = QuinticPolynomial::Interpolation(0.0,0.0,0.0,0.0,1.0,2.0,0.0,0.0); + * @endcode + * + * @sa @ref ecl::QuinticPolynomial "QuinticPolynomial". + */ +template<> +class BluePrintFactory< QuinticPolynomial > { + public: + /** + * @brief Blueprint for an interpolating a quintic between two end points using derivatives. + * + * Generates a blueprint for creating quintic polynomials generated from + * the conditions imposed by initial and final points.. + * + * @param x_i : initial domain value. + * @param y_i : initial polynomial value. + * @param ydot_i : initial polynomial slope. + * @param yddot_i : initial polynomial curvature. + * @param x_f : final domain value. + * @param y_f : final polynomial value. + * @param ydot_f : final polynomial slope. + * @param yddot_f : final polynomial curvature. + * + * @return QuinticInterpolation : the resulting blueprint. + * + * @sa ecl::blueprints::QuinticInterpolation + */ + static QuinticInterpolation Interpolation(const double x_i, const double y_i, const double ydot_i, const double yddot_i, + const double x_f, const double y_f, const double ydot_f, const double yddot_f); + + virtual ~BluePrintFactory() {} +}; + + +/***************************************************************************** +** Interface [Maximum|Minimum][Polynomial] +*****************************************************************************/ +/** + * @brief Mathematical maximum on a compact interval for linear functions. + * + * Mathematical maximum on a compact interval for linear functions (first + * order polynomials). + * + * @sa Maximum, LinearFunction, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Maximum< LinearFunction > { +public: + /** + * @brief Returns the maximum of a linear function. + * + * Returns the maximum of the specified linear function on the given compact interval. + * + * @param x_begin : beginning of the compact interval. + * @param x_end : end of the compact interval. + * @param function : the linear function. + * @return double : the maximum. + **/ + ECL_PUBLIC double operator()(const double& x_begin, const double& x_end, const LinearFunction &function); + virtual ~Maximum() {} +}; + +/** + * @brief Mathematical maximum on a compact interval for cubic polynomials. + * + * Mathematical maximum on a compact interval for cubic polynomials. + * + * @sa Maximum, CubicPolynomial, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Maximum { +public: + /** + * @brief Returns the maximum of a cubic polynomial. + * + * Returns the maximum of the specified cubic polynomial on the given compact interval. + * + * @param x_begin : beginning of the compact interval. + * @param x_end : end of the compact interval. + * @param cubic : the cubic polynomial. + * @return double : the maximum. + */ + ECL_PUBLIC double operator()(const double& x_begin, const double& x_end, const CubicPolynomial& cubic); + virtual ~Maximum() {} +}; + +/** + * @brief Mathematical minimum on a compact interval for linear functions. + * + * Mathematical minimum on a compact interval for linear functions (first + * order polynomials). + * + * @sa Minimum, LinearFunction, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Minimum< LinearFunction > { +public: + /** + * @brief Returns the minimum of a linear function. + * + * Returns the minimum of the specified linear function on the given compact interval. + * + * @param x_begin : beginning of the compact interval. + * @param x_end : end of the compact interval. + * @param function : the linear function. + * @return double : the minimum. + */ + ECL_PUBLIC double operator()(const double& x_begin, const double& x_end, const LinearFunction &function); + virtual ~Minimum() {} +}; + +/** + * @brief Mathematical minimum on a compact interval for cubic polynomials. + * + * Mathematical minimum on a compact interval for cubic polynomials. + * + * @sa Minimum, CubicPolynomial, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Minimum { +public: + /** + * @brief Returns the minimum of a cubic polynomial. + * + * Returns the minimum of the specified cubic polynomial on the given compact interval. + * + * @param x_begin : beginning of the compact interval. + * @param x_end : end of the compact interval. + * @param cubic : the cubic polynomial. + * @return double : the minimum. + */ + ECL_PUBLIC double operator()(const double& x_begin, const double& x_end, const CubicPolynomial& cubic); + virtual ~Minimum() {} +}; + +/***************************************************************************** +** Interface [Intersection][LinearFunction] +*****************************************************************************/ +/** + * @brief Intersection of two linear functions. + * + * @sa Intersection, LinearFunction, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Intersection< LinearFunction > { +public: + Intersection() : last_operation_failed(false) {} + virtual ~Intersection() {} + /** + * @brief Returns the intersection of two linear functions. + * + * @param f : linear function. + * @param g : linear function. + * @return CartesionPoint2d : the intersection point. + * + * @exception : StandardException : throws if functions are collinear. + **/ + ECL_PUBLIC CartesianPoint2d operator()(const LinearFunction& f, const LinearFunction& g); + + /** + * @brief Boolean flag identifying if the last operation failed or not. + * + * Use this if you have disabled exceptions or don't wish to catch + * the exception thrown when linear functions are collinear. + */ + bool fail() const { return last_operation_failed; } + +private: + bool last_operation_failed; +}; + +/***************************************************************************** +** Interface [Synthetic Division] +*****************************************************************************/ +/** + * @brief Synthetic division between quadratic and a factor. + * + * Does long division of the polynomial by (x-factor) + */ +template<> +class ecl_geometry_PUBLIC Division { +public: + Division() {}; + virtual ~Division() {}; + /** + * @brief Synthetic division by a factor. + * @param p : the polynomial + * @param factor : of the form (x-factor) + * @param remainder : remainder left after the division + * @return LinearFunction : result of the division (along with remainder) + */ + ECL_PUBLIC LinearFunction operator()(const QuadraticPolynomial &p, const double &factor, double &remainder); +}; + +/** + * @brief Synthetic division between cubic and a factor. + * + * Does long division of the polynomial by (x-factor) + */ +template<> +class ecl_geometry_PUBLIC Division { +public: + Division() {}; + virtual ~Division() {}; + /** + * @brief Synthetic division by a factor. + * @param p : the polynomial + * @param factor : of the form (x-factor) + * @param remainder : remainder left after the division + * @return QuadraticPolynomial : result of the division (along with remainder) + */ + ECL_PUBLIC QuadraticPolynomial operator()(const CubicPolynomial &p, const double &factor, double &remainder); +}; + +/***************************************************************************** +** Interface [Roots] +*****************************************************************************/ +/** + * @brief X axis intercepts for linear functions. + * + * @sa Roots, Linear Function, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Roots { +public: + Roots() {} + virtual ~Roots() {} + /** + * @brief Returns the root of the specified polynomial. + * + * @param p : linear function. + * @return vector : list of x axis intercepts. + **/ + ECL_PUBLIC Array operator()(const LinearFunction& p); +}; + +/** + * @brief X axis intercepts for quadratics. + * + * @sa Roots, QuadraticPolynomial, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Roots { +public: + Roots() {} + virtual ~Roots() {} + /** + * @brief Returns the root of the specified polynomial. + * + * @param p : quadratic polyonmial. + * @return vector : list of x axis intercepts. + **/ + ECL_PUBLIC Array operator()(const QuadraticPolynomial& p); +}; +/** + * @brief X axis intercepts for cubic polynomials. + * + * @sa Roots, CubicPolynomial, @ref polynomialsGeometry "Math::Polynomials". + */ +template<> +class ecl_geometry_PUBLIC Roots { +public: + Roots() {} + virtual ~Roots() {} + /** + * @brief Returns the root of the specified polynomial. + * + * @param p : cubic polynomial. + * @return vector : list of x axis intercepts. + **/ + ECL_PUBLIC Array operator()(const CubicPolynomial& p); +}; + +/***************************************************************************** +** Interfaces [FunctionMath] +*****************************************************************************/ +/** + * @brief Specialises the function math loader for linear functions. + * + * This lets you use the functions directly from within the class, e.g. + * + * + * LinearFunction f = LinearFunction::Interpolation(0.0,0.0,1.0,2.0); + * LinearFunction g = LinearFunction::Interpolation(0.0,2.0,1.0,0.0); + * CartsianPoint2d point = LinearFunction::Intersection(f,g); + * + */ +template <> +class ECL_PUBLIC FunctionMath { +public: + FunctionMath() {}; /** @brief Default constructor. **/ + virtual ~FunctionMath() {}; + /** + * @brief Redirections intersection operator for linear functions. + * + * @sa Intersection + */ + static CartesianPoint2d Intersection(const LinearFunction &f, const LinearFunction &g) { + CartesianPoint2d point; + ecl_try { + ecl::Intersection< LinearFunction > intersection; + point = intersection(f,g); + } ecl_catch( const StandardException &e ) { + ecl_throw(StandardException(LOC,e)); + } + return point; + } + /** + * @brief Root of the linear function. + * + * @sa Roots + */ + static Array Roots(const LinearFunction &function) { + return ecl::Roots()(function); + } + /** + * @brief Redirections the minimum operator for linear functions. + * + * @sa Minimum + */ + static double Minimum(const double& x_begin, const double& x_end, const LinearFunction &function) { + return ecl::Minimum()(x_begin, x_end, function); + } + /** + * @brief Redirections the maximum operator for linear functions. + * + * @sa Maximum + */ + static double Maximum(const double& x_begin, const double& x_end, const LinearFunction &function) { + return ecl::Maximum()(x_begin, x_end, function); + } +}; +/** + * @brief Specialises the function math loader for quadratics. + * + * This lets you use the functions directly from within the class. + * + * @sa FunctionMath + */ +template <> +class ECL_PUBLIC FunctionMath { +public: + FunctionMath() {}; /** @brief Default constructor. **/ + virtual ~FunctionMath() {}; + /** + * @brief Real roots of the quadratic. + * + * @sa Roots + */ + static Array Roots(const QuadraticPolynomial &p) { + return ecl::Roots()(p); + } + /** + * @brief Division by a factor (synthetic division algorithm). + */ + static LinearFunction Division(const QuadraticPolynomial &p, const double &factor, double &remainder) { + LinearFunction f(ecl::Division()(p,factor,remainder)); + return f; + } +}; + +/** + * @brief Specialises the function math loader for cubics. + * + * This lets you use the functions directly from within the class. + * + * @sa FunctionMath + */ +template <> +class ECL_PUBLIC FunctionMath { +public: + FunctionMath() {}; /** @brief Default constructor. **/ + virtual ~FunctionMath() {}; + /** + * @brief Real roots of the cubic. + * + * @sa Roots + */ + static Array Roots(const CubicPolynomial &p) { + return ecl::Roots()(p); + } + /** + * @brief Division by a factor (synthetic division algorithm). + */ + static QuadraticPolynomial Division(const CubicPolynomial &p, const double &factor, double &remainder) { + QuadraticPolynomial q(ecl::Division()(p,factor,remainder)); + return q; + } + /** + * @brief Redirections the minimum operator for cubics. + * + * @sa Minimum + */ + static double Minimum(const double& x_begin, const double& x_end, const CubicPolynomial &function) { + return ecl::Minimum()(x_begin, x_end, function); + } + /** + * @brief Redirections the maximum operator for cubics. + * + * @sa Intersection + */ + static double Maximum(const double& x_begin, const double& x_end, const CubicPolynomial &function) { + return ecl::Maximum()(x_begin, x_end, function); + } +}; + +} // namespace ecl + +#endif /*ECL_GEOMETRY_POLYNOMIALS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pose2d.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pose2d.hpp new file mode 100644 index 0000000..dd4544c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/pose2d.hpp @@ -0,0 +1,198 @@ +/** + * @file /ecl_geometry/include/ecl/geometry/pose.hpp + * + * The ECL pose library is a library of methods built on top of + * Eigen & Sophus data structures. This has proven to be more flexible + * than having custom c++ Pose2D / Pose3D classes unique to the ECL + * as it permits conversion-free interactions with other libraries + * that have also standardised on Eigen & Sophus. + */ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ecl_geometry_GEOMETRY_POSE2D_HPP_ +#define ecl_geometry_GEOMETRY_POSE2D_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include + +#include "angle.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl { + +/***************************************************************************** + ** Pose2D - Eigen::Vector3d (x, y, heading) storage + *****************************************************************************/ +/** + * @brief Concatenate 2d poses. + * + * This computes the pose of frame C relative to frame A. Poses + * are (x, y, heading) triples in Eigen::Vector3f or Eigen::Vector3d + * containers. + * + * @param pose_b_rel_a: pose of frame B relative to frame A + * @param pose_c_rel_b: pose of frame C relative to frame B + * @param dummy: enforces compile time check for floats or doubles + * @return Eigen::Matrix: pose of frame C relative to frame A + */ +template +linear_algebra::Matrix concatenate_poses( + const linear_algebra::Matrix &pose_b_rel_a, + const linear_algebra::Matrix &pose_c_rel_b, + typename enable_if >::type* dummy = 0) +{ + (void) dummy; + linear_algebra::Matrix pose_c_rel_a; + Float c = std::cos(pose_b_rel_a[2]); + Float s = std::sin(pose_b_rel_a[2]); + pose_c_rel_a << + pose_b_rel_a[0] + c*pose_c_rel_b[0] - s*pose_c_rel_b[1], + pose_b_rel_a[1] + s*pose_c_rel_b[0] + c*pose_c_rel_b[1], + wrap_angle(pose_b_rel_a[2] + pose_c_rel_b[2]); + // c++03 copy elision will guarantee no copy is made + return pose_c_rel_a; +} + +/** + * @brief Extend poses. + * + * This concatenates the original pose with another pose, in place. + * i.e. if pose_b_rel_a is extended by pose_c_rel_b then + * pose_b_rel_a *becomes* pose_c_rel_a. + * + * @param pose: the original pose (will be updated) + * @param extending_pose: pose to extend with + * @param dummy: enforces compile time check for floats or doubles + */ +template +void extend_pose( + linear_algebra::Matrix &pose, + const linear_algebra::Matrix &extending_pose, + typename enable_if >::type* dummy = 0) +{ + (void) dummy; + Float c = std::cos(pose[2]); + Float s = std::sin(pose[2]); + pose << + pose[0] + c*extending_pose[0] - s*extending_pose[1], + pose[1] + s*extending_pose[0] + c*extending_pose[1], + wrap_angle(pose[2] + extending_pose[2]); +} + +/***************************************************************************** + ** Pose2D Class + *****************************************************************************/ + +/** + * @brief A simple convenience class for 2d poses. + * + * This could get more complicated, but likely you'll want + * your own (use the methods above). One extension here that + * might be useful is an alternative backend (enable via + * a Storage template type that can be either an eigen + * Vector3 or Transform depending on the user's + * requirements. + */ +template +class Pose2D { +public: + /**************************************** + * Typedefs + ***************************************/ + using XYH = linear_algebra::Matrix; + using Translation = linear_algebra::Matrix; + using RotationMatrix = linear_algebra::Matrix; + + /**************************************** + * Constructors & Destructors + ***************************************/ + /** + * @brief Default constructor + * + * @param xyh: x, y, heading wrapped in an eigen vector3d type. + */ + Pose2D(): xyh(0.0) {} + + /** + * @brief Construction by element. + * + * @param x: x-translation + * @param y: y-translation + * @param h: heading (radians) + */ + Pose2D(const float& x, const float& y, const float& h) { + xyh << x, y, h; + } + + /** + * @brief Construction by container. + * + * @param xyh: x, y, heading wrapped in an eigen vector3d type. + */ + Pose2D(const XYH& xyh) : xyh(xyh) {} + + // moving eigen vectors only possible for VectorXd types (using Vector3d here) + + /** + * @brief Concatenate this pose with another. + * + * If this pose represents pose_b_rel_a, and the incoming pose is pose_c_rel_b, + * then the return pose via this operator would be pose_c_rel_a. + * + * @param pose : relative to this pose's frame of reference + * @return Pose2D : the concatenated pose + */ + Pose2D operator*(const Pose2D &pose) const { + return concatenate_poses(this->xyh, pose); + } + + /** + * @brief Extend this pose with the incoming pose. + * + * If this pose represents pose_b_rel_a, and the incoming pose is pose_c_rel_b, + * then the updated pose via this operator would be pose_c_rel_a. + * + * @param pose : relative to this pose's frame of reference + * @return Pose2D& : handle to the updated pose + */ + Pose2D& operator*=(const Pose2D &pose) { + extend_pose(this->xyh, pose.xyh); + return (*this); + } + + /****************************************** + ** Accessors + *******************************************/ + const Float& x() const { return xyh[0]; } //!< @brief Get the x-coordinate. + const Float& y() const { return xyh[1]; } //!< @brief Get the y-coordinate. + const Float& heading() const { return xyh[2]; } //!< @brief Get the heading. + const Translation& translation() const { return xyh. template head<2>(); } + /** + * @brief Representation of the heading in matrix form. + **/ + const RotationMatrix& rotationMatrix() const { + Float c = std::cos(xyh[2]); + Float s = std::sin(xyh[2]); + return (RotationMatrix() << c, -s, s, c).finished(); + } + +private: + XYH xyh; +}; + +/***************************************************************************** + ** Trailers + *****************************************************************************/ + +} // namespace ecl + +#endif /* ecl_geometry_GEOMETRY_POSE2D_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/smooth_linear_spline.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/smooth_linear_spline.hpp new file mode 100644 index 0000000..9804cc1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/smooth_linear_spline.hpp @@ -0,0 +1,191 @@ +/** + * @file /include/ecl/geometry/smooth_linear_spline.hpp + * + * @brief Spline sequence generated from linear segments with ramped corners. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SMOOTH_LINEAR_SPLINE_HPP_ +#define ECL_SMOOTH_LINEAR_SPLINE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "polynomial.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [SmoothLinearSpline] +*****************************************************************************/ +/** + * @brief Storage container for a smoothed linear spline interpolation. + * + * These interpolations connect waypoints linearly and add a smoothed corner (using + * a quintic polynomial) to connect each linear segment. The shape of the corners + * is parameterised with a maximum curvature parameter (acceleration). + * + * @ref splinesGeometry "Math::Splines. + **/ +class ecl_geometry_PUBLIC SmoothLinearSpline { +public: + /** + * @brief Default constructor. + * + * Don't really need this, but things like vectors and array containers need + * it so they can reserve the appropriate storage. + */ + SmoothLinearSpline() {} + /** + * @brief Constructor that properly configures the ramped spline. + * + * The constructor uses the input data sets to initialise the segmentation. + * Corners are constrained by the maximum curvature (acceleration) - if + * construction should fail (not enough space between the waypoints) then + * this method will throw an exception indicating failure. + * It is accompanied with an int type data element that indicates the + * number of the segment that failed to construct. Failure typically occurs + * because the maximum curvature constraint at the corner was broken. Try + * increasing the maximum curvature constraint or increasing the time + * duration of the specified segment to ensure success a + * second time around. + * + * @param a_max : the maximum bound (absolute) on the acceleration. + * @param x_data : set of data on the domain axis. + * @param y_data : set of values on the range axis. + * @exception : DataException : throws if the spline could not be constructed because of broken a_max constraint. + * + * The int data for the exception represents the element in the set which could not make + * a corner without breaking the acceleration constraint. Note that if you have a data set of size 5 (i.e. + * elements 0-4), then it will only throw between 1 and 3, as this is where smoothed corners are built. + */ + SmoothLinearSpline(const Array& x_data, const Array& y_data, double a_max); + + virtual ~SmoothLinearSpline() {} + + /** + * @brief Spline function. + * + * Extract the spline function's value at the indicated location. + * + * @param x : the domain value. + * @return double : the spline function's value. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double operator()(const double &x) const; + /** + * @brief Spline derivative. + * + * Extract the derivative of the spline at the indicated value. + * + * @param x : the domain value. + * + * @return double : the derivative of the spline. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double derivative(const double &x) const; + /** + * @brief Spline second derivative. + * + * Extract the second derivative of the spline. + * @param x : the domain value. + * @return double : the second derivative of the spline. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double dderivative(const double &x) const; + + /** + * @brief The discretised domain for this spline. + * + * This returns the array of discretised time values that define + * the domains of each polynomial within the spline. + * + * @return const Array& : the discretised domain. + */ + const Array& domain() const { return discretised_domain; } + + /********************* + * Static Constructor + **********************/ + /** + * @brief Static construction that interpolates on a set of waypoints. + * + * Static construction that interpolates on a set of waypoints. + * + * @param x_data : set of data on the domain axis. + * @param y_data : set of values on the range axis. + * @param a_max : the maximum bound (absolute) on the acceleration. + * + * @exception : DataException : throws if the spline could not be constructed, data is the segment # that failed. + */ + static SmoothLinearSpline Interpolation(const Array& x_data, const Array& y_data, double a_max) + { + try { + return SmoothLinearSpline(x_data, y_data, a_max); + } catch ( DataException &e ) { + throw DataException(LOC,e); + } + return SmoothLinearSpline(); // avoid a warning because of the rethrown exception. + } + + /****************************************** + * Streaming + *******************************************/ + /** + * @brief Streaming output insertion operator for smoothed linear splines. + * + * Streaming output insertion operator for smoothed linear splines. This + * simply lists the spline segments and corners (linear functions and + * quintic polynomials) in algebraic form. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param smooth_linear_spline : the tension spline. + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, const SmoothLinearSpline &smooth_linear_spline); + +private: + Array discretised_domain; // 2*N points (2 end points + 2*(N-1) corner points) + Array segments; // N linear segments + Array corners; // N-1 corners +}; + +/***************************************************************************** +** Implementation [SmoothLinearSpline][Streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, const SmoothLinearSpline &smooth_linear_spline) { + + ecl_compile_time_concept_check(StreamConcept); + + ostream << smooth_linear_spline.segments[0] << "\n"; + for ( unsigned int i = 1; i < smooth_linear_spline.segments.size(); ++i ) { + ostream << smooth_linear_spline.corners[i-1] << "\n"; + ostream << smooth_linear_spline.segments[i] << "\n"; + } + ostream.flush(); + return ostream; +} + +} // namespace ecl + +#endif /* ECL_SMOOTH_LINEAR_SPLINE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/spline_function.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/spline_function.hpp new file mode 100644 index 0000000..14ff6ec --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/spline_function.hpp @@ -0,0 +1,144 @@ +/** + * @file /include/ecl/geometry/spline_function.hpp + * + * @brief Wrapper for a generic spline function. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_SPLINE_FUNCTION_HPP_ +#define ECL_GEOMETRY_SPLINE_FUNCTION_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [GenericSplineFunction] +*****************************************************************************/ +/** + * @brief This is a parent class for generic spline functions. + * + * This is the parent interface for spline functions. + * + * @sa SplineFunction + **/ +class ECL_PUBLIC GenericSplineFunction { + public: + virtual ~GenericSplineFunction() {}; + /** + * @brief Virtual access function for a spline function. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the function at x. + */ + virtual double operator()(const double &x) const = 0; + /** + * @brief Virtual access function for a spline function derivative. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the derivative at x. + */ + virtual double derivative(const double &x) const = 0; + /** + * @brief Virtual access function for a spline function's 2nd derivative. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the 2nd derivative at x. + */ + virtual double dderivative(const double &x) const = 0; + + /** + * @brief Get access to the domain for this spline function. + * + * Get access to the domain for this spline function. + * + * @return const Array& : stores domain_begin and domain_end. + */ + const Array& domain() { return time_domain; } + + protected: + Array time_domain; +}; +/***************************************************************************** +** Interface [SplineFunction] +*****************************************************************************/ +/** + * @brief Template wrapper for a generic spline function. + * + * Template wrapper for a generic spline function. Didn't want + * to inherit an interface for all the underlying functions (polynomials, + * tension functions, splines etc) so this is an indirect way of + * getting the polymorphism to work. It is not usually used directly, but + * rather internally in the trajectory classes. + * + * @tparam Function : the internally wrapped function. + **/ +template +class ECL_PUBLIC SplineFunction : public GenericSplineFunction { + public: + /** + * @brief Constructor, copies across an already existing spline function type and wraps it. + * + * Copies an existing spline function into this wrapper along with domain boundaries. + * + * @param time_begin : beginning of the domain the spline function is valid on. + * @param time_end : end of the domain the spline function is valid on. + * @param f : the spline function to wrap. + */ + SplineFunction (const double& time_begin, const double& time_end, const Function& f) : function(f) { + time_domain << time_begin, time_end; + }; + virtual ~SplineFunction() {}; + + /** + * @brief Access the value of the spline function at the specified value. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the function at x. + * @exception : StandardException : throws if input x value is outside the domain [debug mode only]. + */ + double operator()(const double &x) const { + ecl_assert_throw( ( x >= time_domain[0] ) && x <= time_domain[1], StandardException(LOC,OutOfRangeError ) ); + return function(x); + } + + /** + * @brief Access the value of the spline function's derivative at the specified value. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the derivative at x. + * @exception : StandardException : throws if input x value is outside the domain [debug mode only]. + */ + double derivative(const double &x) const { + ecl_assert_throw( ( x >= time_domain[0] ) && x <= time_domain[1], StandardException(LOC,OutOfRangeError ) ); + return function.derivative(x); + } + + /** + * @brief Access the value of the spline function's 2nd derivative at the specified value. + * @param x : the point at which you wish to calculate the value for. + * @return double : the value of the 2nd derivative at x. + * @exception : StandardException : throws if input x value is outside the domain [debug mode only]. + */ + double dderivative(const double &x) const { + ecl_assert_throw( ( x >= time_domain[0] ) && x <= time_domain[1], StandardException(LOC,OutOfRangeError ) ); + return function.dderivative(x); + } + + private: + Function function; +}; + +} // namespace ecl + + +#endif /* SPLINE_FUNCTION_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_function.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_function.hpp new file mode 100644 index 0000000..6a0b309 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_function.hpp @@ -0,0 +1,340 @@ +/** + * @file /include/ecl/geometry/tension_function.hpp + * + * @brief Representations for the tension function.. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_TENSION_FUNCTION_HPP_ +#define ECL_GEOMETRY_TENSION_FUNCTION_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "function_math.hpp" +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +class TensionFunction; + +namespace blueprints { + +class TensionSecondDerivativeInterpolation; + +} // namespace blueprints + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ +/** + * @brief Blueprint factory for tension functions. + * + * Generates various blueprints that instantiate or configure tension functions with + * commonly used configurations. + * + * @sa @ref ecl::TensionFunction "TensionFunction". + */ +template<> +class ECL_PUBLIC BluePrintFactory< TensionFunction > { + public: + /** + * @brief Blueprint for interpolating a tension function between two end points using second derivatives. + * + * Generates a blueprint for creating tension functions generated from + * value and second derivative constraints on the endpoints. + * + * @param x_i : initial domain value. + * @param y_i : initial value. + * @param yddot_i : initial curvature. + * @param x_f : final domain value. + * @param y_f : final value. + * @param yddot_f : final curvature. + * + * @return TensionSecondDerivativeInterpolation : the resulting blueprint. + * + * @sa ecl::blueprints::TensionSecondDerivativeInterpolation + */ + static blueprints::TensionSecondDerivativeInterpolation Interpolation(const double x_i, const double y_i, const double yddot_i, + const double x_f, const double y_f, const double yddot_f); + + virtual ~BluePrintFactory() {}; +}; + +/***************************************************************************** +** Interface [TensionFunction] +*****************************************************************************/ +/** + * @brief Representation of a tension function. + * + * This is a hyperbolic function + * often used in spline interpolations that parameterises the 'tension' of + * a curve interpolation between points. At low tension it behaves like a + * cubic polynomial, while at high tension, it tends towards a piecewise + * smooth series of linear functions. + * + * Theoretical Notes: + * + * Tension functions are derived from the following constraints on + * an interval [x_i, x_i+1]: + * @verbatim + f'''' - tau^2 f'' = 0 + f(x_i) = y_i + f(x_i+1) = y_i+1 + f''(x_i) = z_i + f''(x_i+1) = z_i+1 + @endverbatim + * This yields a C2 continuous function with hyperbolic terms (not a polynomial) + * that ranges from looking like a cubic interpolation at low tensions + * (tau -> 0) and a linearly blended interpolation at high tensions. + **/ +class ECL_PUBLIC TensionFunction : public BluePrintFactory< TensionFunction > { + public: + /********************* + ** Constructors + **********************/ + /** + * @brief Default constructor. + * + * Don't really need this, but things like vectors and array containers need + * it so they can reserve the appropriate storage. + */ + TensionFunction() {} + virtual ~TensionFunction() {} + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * TensionFunction f = TensionFunction::Interpolation(2.0,0.0,0.0,3.0,1.0,0.0); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * TensionFunction f; + * f = TensionFunction::Interpolation(2.0,0.0,0.0,3.0,1.0,0.0); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprints concept (refer to ecl_concepts' documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa ecl::utilities::BluePrintFactory. + */ + template + TensionFunction(const BluePrint< Derived > &blueprint) { + blueprint.implementApply(*this); + } + + /********************* + ** Derivatives + **********************/ + /** + * @brief Generates the derivative for a certain tension at the specified point. + * + * Calculates the value of the derivative for a certain tension at the specified point. + * + * @param tau : the tension parameter. + * @param x : the point at which you wish to calculate the value for. + * + * @return double : the value of the derivative at x for tension tau. + */ + double derivative(const double &tau, const double &x) const; + + /** + * @brief Generates the 2nd derivative for a certain tension at the specified point. + * + * Calculates the value of the 2nd derivative for a certain tension at the specified point. + * + * @param tau : the tension parameter. + * @param x : the point at which you wish to calculate the value for. + * + * @return double : the value of the 2nd derivative at x for tension tau. + */ + double dderivative(const double &tau, const double &x) const; + + /********************* + ** Accessors + **********************/ + /** + * @brief Calculates the value for a certain tension at the specified point. + * + * Calculates the value for a certain tension at the specified point. + * + * @param tau : the tension parameter. + * @param x : the point at which you wish to calculate the value for. + * + * @return double : the value of the function at x for tension tau. + **/ + double operator ()(const double &tau, const double &x) const; + + /********************* + ** Friends + **********************/ + friend class blueprints::TensionSecondDerivativeInterpolation; + + + template + friend OutputStream& operator << (OutputStream &ostream, const TensionFunction &function); + + private: + double z_0, z_f; // yddot_0, yddot_f + double x_0, x_f; + double y_0, y_f; +}; + + +/***************************************************************************** +** Streaming Operator [TensionFunction] +*****************************************************************************/ +/** + * @brief Streaming output insertion operator for tension functions. + * + * Streaming output insertion operator for tension functions. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param function : the tension function. + * @return OutputStream : the output stream. + */ +template +OutputStream& operator << (OutputStream &ostream, const TensionFunction &function) +{ + ecl_compile_time_concept_check(StreamConcept); + + Format format; + format.precision(2); + double h = function.x_f - function.x_0; + if ( ( function.z_0 == 0.0 ) && ( function.z_f == 0.0 ) ) { + ostream << "0.0"; + } else { + ostream << "{"; + if ( function.z_0 != 0.0 ) { + ostream << format(function.z_0) << "*sinh[tau("; + ostream << format(function.x_f) << "-x)] + "; + } + if ( function.z_f != 0.0 ) { + ostream << format(function.z_f) << "*sinh[tau(x-"; + ostream << format(function.x_0) << ")]}/[tau^2 sinh("; + ostream << format(function.x_f - function.x_0) << "*tau)]"; + } + } + ostream << "\n"; + ostream << " + ("; + ostream << format(function.y_0/h) << "-"; + ostream << format(function.z_0/h) << "/tau^2)("; + ostream << format(function.x_f) << "-x)\n"; + ostream << " + ("; + ostream << format(function.y_f/h) << "-"; + ostream << format(function.z_f/h) << "/tau^2)(x-"; + ostream << format(function.x_0) << ")\n"; + ostream.flush(); + + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [TensionSecondDerivativeInterpolation] +*****************************************************************************/ + +/** + * @brief Blueprint for interpolating a tension function between end point conditions. + * + * Blueprint for interpolating a tension function between two end point conditions. That is, + * the resulting y(x) should satisfy the following conditions: + * + * @code + * y(x_i) = y_i + * y(x_f) = y_f + * y''(x_i) = y''_i + * y''(x_f) = y''_f + * @endcode + * + * @sa @ref ecl::TensionFunction "TensionFunction". + * + **/ +class ECL_PUBLIC TensionSecondDerivativeInterpolation : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::TensionFunction base_type; + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * Constructor that accepts the boundary constraints used to generate the tension function. + * + * @param x_i : initial domain value. + * @param y_i : initial value. + * @param yddot_i : initial curvature. + * @param x_f : final domain value. + * @param y_f : final value. + * @param yddot_f : final curvature. + */ + TensionSecondDerivativeInterpolation(const double x_i, const double y_i, const double yddot_i, + const double x_f, const double y_f, const double yddot_f) : + x_initial(x_i), + y_initial(y_i), + yddot_initial(yddot_i), + x_final(x_f), + y_final(y_f), + yddot_final(yddot_f) + {} + virtual ~TensionSecondDerivativeInterpolation() {} + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new tension function generated from the input boundary conditions. + * + * @return TensionFunction : a copy of the generated function. + */ + ecl::TensionFunction instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the boundary conditions to generate the tension function. + * + * @param function : the function to configure from the supplied boundary conditions. + */ + void apply(base_type& function) const; + + private: + double x_initial, y_initial, yddot_initial; + double x_final, y_final, yddot_final; +}; + + +} // namespace blueprints +} // namespace ecl + +#endif /*ECL_GEOMETRY_TENSION_FUNCTION_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_spline.hpp b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_spline.hpp new file mode 100644 index 0000000..325565d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/include/ecl/geometry/tension_spline.hpp @@ -0,0 +1,309 @@ +/** + * @file /include/ecl/geometry/tension_spline.hpp + * + * @brief Storage container for a tension spline interpolation. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_GEOMETRY_TENSION_SPLINE_HPP_ +#define ECL_GEOMETRY_TENSION_SPLINE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "tension_function.hpp" +#include +#include +#include +#include +#include +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +class TensionSpline; + +namespace blueprints { + +class C2TensionSpline; + +} // namespace blueprints + +/***************************************************************************** +** BluePrintFactory +*****************************************************************************/ +/** + * @brief Blueprint factory for tension splines. + * + * Generates various blueprints that instantiate or configure tension splines from commonly + * used algorithms. + * + * @sa @ref ecl::TensionSpline "TensionSpline". + */ +template<> +class ECL_PUBLIC BluePrintFactory< TensionSpline > { +public: + /** + * @brief Tension spline blueprint satisfying y, y' and y'' continuity with y''_0 = y''_f = 0. + * + * This is the natural form of the spline interpolation. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param tau : the tension parameter. + * @return C2TensionSpline : the resulting blueprint. + * @exception : StandardException : throws if configuration arguments are not valid [debug mode only]. + * + * @sa @ref ecl::blueprints::C2TensionSpline "C2TensionSpline" + */ + static blueprints::C2TensionSpline Natural(const Array& x_set, const Array& y_set, + const double &tau); + + virtual ~BluePrintFactory() {}; +}; + +/***************************************************************************** +** Interface [TensionSpline] +*****************************************************************************/ +/** + * @brief Storage container for a tension spline interpolation. + * + * These interpolations + * are very similar to cubic splines, but allow an extra parameter for configuration + * called the tension of the interpolation. The tension variable effectively + * tightens the curve among the data points, resulting in a spline interpolation + * that looks very similar to the linear blended interpolations. When the tension + * approaches zero, this interpolation defaults to a cubic spline interpolation. + * + * @sa @ref ecl::CubicSpline "CubicSpline", @ref splinesGeometry "Math::Splines. + **/ +class ecl_geometry_PUBLIC TensionSpline : public BluePrintFactory< TensionSpline > { + public: + /****************************************** + ** Typedefs + *******************************************/ + typedef BluePrintFactory< TensionSpline > Factory; /**< @brief Generates blueprints for this class. **/ + + /****************************************** + ** Constructors + *******************************************/ + /** + * @brief Default constructor. + * + * Don't really need this, but things like vectors and array containers need + * it so they can reserve the appropriate storage. + **/ + TensionSpline () {}; + virtual ~TensionSpline() {}; + /** + * @brief Blueprint constructor. + * + * Constructor that allows automatic generation from an + * existing blueprint. This can be used simply in the following manner + * for any static element belonging to the BluePrintFactory. + * @code + * double tension = 4.0; + * Array x_set(5); + * Array y_set(5); + * x_set = 0.0, 1.0, 2.0, 3.0, 4.0; + * y_set = 1.0, 2.0, 1.0, 3.0, 4.0; + * TensionSpline tension_spline = TensionSpline::Natural(x_set,y_set,tension); + * @endcode + * Since this is not explicit, it will also allow assignment. + * @code + * tension_spline = TensionSpline::Natural(x_set,y_set,tension); + * @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the blueprints concept (refer to ecl_concepts' documentation). + * + * @param blueprint : the blue print to use to generate this instance. + * + * @sa ecl::BluePrintFactory. + */ + template + TensionSpline(const BluePrint< Derived > &blueprint) { + blueprint.implementApply(*this); + } + + /****************************************** + ** Access + *******************************************/ + friend class blueprints::C2TensionSpline; + + /** + * @brief Spline function. + * + * Extract the spline function's value at the indicated location. + * + * @param x : the domain value. + * @return double : the spline function's value. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double operator()(const double &x) const; + /** + * @brief Spline derivative. + * + * Extract the derivative of the spline at the indicated value. + * + * @param x : the domain value. + * + * @return double : the derivative of the spline. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double derivative(const double &x) const; + /** + * @brief Spline second derivative. + * + * Extract the second derivative of the spline. + * @param x : the domain value. + * @return double : the second derivative of the spline. + * @exception : StandardException : throws if x is outside the spline range [debug mode only]. + */ + double dderivative(const double &x) const; + + /** + * @brief The discretised domain for this spline. + * + * This returns the array of discretised time values that define + * the domains of each polynomial within the spline. + * @return const Array& : the discretised domain. + */ + const Array& domain() const { return discretised_domain; } + + /****************************************** + ** Streaming + *******************************************/ + /** + * @brief Streaming output insertion operator for for tension splines. + * + * Streaming output insertion operator for tension splines. This lists in algebraic + * form the sequence of tension functions constituting the spline. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param tension_spline : the tension spline. + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, const TensionSpline &tension_spline); + + private: + Array discretised_domain; // N+1 x_i's + Array functions; // N tension_functions + double tension; +}; + +/***************************************************************************** +** Interface [Minimum/Maximum][TensionSpline] +*****************************************************************************/ + +/***************************************************************************** +** Implementation [TensionSpline][Streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, const TensionSpline &tension_spline) { + + ecl_compile_time_concept_check(ecl::StreamConcept); + + for ( unsigned int i = 0; i < tension_spline.functions.size(); ++i ) { + ostream << tension_spline.functions[i] << "\n"; + } + ostream.flush(); + return ostream; +} + +/***************************************************************************** +** BluePrints +*****************************************************************************/ + +namespace blueprints { + +/***************************************************************************** +** Interface [C2TensionSpline] +*****************************************************************************/ + +/** + * @brief Blueprint for generating a tension spline satisfying C2 constraints. + * + * Blueprint for generating a tension spline on a set of data given the constraint + * of continuity of y, y' and y''. + * + * @sa @ref ecl::TensionSpline "TensionSpline". + * + **/ +class ecl_geometry_PUBLIC C2TensionSpline : public ecl::BluePrint { + public: + /** + * @brief Abstract representation of the class to be instantiated/configured. + **/ + typedef ecl::TensionSpline base_type; + /** + * @brief Default constructor. + * + * Default constructor (only utilised by the blueprint compile time assert). + */ + C2TensionSpline() {}; + ~C2TensionSpline() {}; + + /** + * @brief Constructor that properly configures/initialises the blueprint. + * + * The constructor uses the input data sets along with the assumption of + * zero boundary conditions on the second derivatives to generate a full + * set of second derivatives at each via point that will guarantee c2 + * continuity of the spline. + * + * @param x_set : set of data on the domain axis. + * @param y_set : set of values on the range axis. + * @param tau : the tension parameter. + * @exception : StandardException : throws if configuration arguments are not valid [debug mode only]. + */ + C2TensionSpline(const ecl::Array& x_set, const ecl::Array& y_set, const double &tau); + + /** + * @brief Instantiate a copy of the object that is blueprinted. + * + * Instantiates a new tension spline generated from the supplied data set. + * + * @return TensionSpline : a copy of the generated tension spline. + */ + base_type instantiate(); + + /** + * @brief Apply the blueprint to configure an existing object. + * + * Apply the data set to generate the configuration required for the tension spline. + * + * @param spline : the spline to configure from the supplied data set. + */ + void apply(base_type& spline) const; + + private: + ecl::Array x_data; + ecl::Array y_data; + ecl::Array yddot_data; + double tension; +}; + +} // namespace blueprints +} // namespace ecl + +#endif /* ECL_GEOMETRY_TENSION_SPLINE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_geometry/package.xml b/ros2_ws/src/ecl_core/ecl_geometry/package.xml new file mode 100644 index 0000000..8b13041 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/package.xml @@ -0,0 +1,49 @@ + + + ecl_geometry + 1.2.1 + + Any tools relating to mathematical geometry. + Primarily featuring polynomials and interpolations. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_geometry + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_build + ecl_license + ecl_config + ecl_containers + ecl_exceptions + ecl_formatters + ecl_linear_algebra + ecl_math + ecl_mpl + ecl_type_traits + + ecl_build + ecl_license + ecl_config + ecl_containers + ecl_exceptions + ecl_formatters + ecl_linear_algebra + ecl_math + ecl_mpl + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/rosbuild.cmake b/ros2_ws/src/ecl_core/ecl_geometry/rosbuild.cmake new file mode 100644 index 0000000..a979227 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/rosbuild.cmake @@ -0,0 +1,7 @@ +if(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/package.cmake) + include(${CMAKE_CURRENT_BINARY_DIR}/package.cmake) +endif() + +add_subdirectory(include) +add_subdirectory(src/lib) +add_subdirectory(pkg-config) diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/src/CMakeLists.txt new file mode 100644 index 0000000..a0e6b6f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/CMakeLists.txt @@ -0,0 +1,12 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/CMakeLists.txt new file mode 100644 index 0000000..915f798 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/CMakeLists.txt @@ -0,0 +1,43 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Install +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_containers::ecl_containers + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_linear_algebra::ecl_linear_algebra + ecl_math::ecl_math + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/angle.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/angle.cpp new file mode 100644 index 0000000..0c87478 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/angle.cpp @@ -0,0 +1,76 @@ +/** + * @file /src/lib/angle.cpp + * + * @brief Implementation for regular radian/degree angle types. + * + * Implementation for regular radian/degree angle types. + * + * @date February 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/angle.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Functions] +*****************************************************************************/ + +const float& wrap_angle(float &angle) { + if ( ( angle <= pi ) && ( angle >= -pi ) ) { + return angle; // nothing to do. + } + if ( angle < 0.0 ) { + angle = fmodf(angle-pi,2.0*pi)+pi; + } else { + angle = fmodf(angle+pi,2.0*pi)-pi; + } + return angle; +} +float wrap_angle(const float &angle) { + float wrapped; + if ( ( angle <= pi ) && ( angle >= -pi ) ) { + wrapped = angle; + } else if ( angle < 0.0 ) { + wrapped = fmodf(angle-pi,2.0*pi)+pi; + } else { + wrapped = fmodf(angle+pi,2.0*pi)-pi; + } + return wrapped; +} + +const double& wrap_angle(double &angle) { + if ( ( angle <= pi ) && ( angle >= -pi ) ) { + return angle; // nothing to do. + } + if ( angle < 0.0 ) { + angle = fmod(angle-pi,2.0*pi)+pi; + } else { + angle = fmod(angle+pi,2.0*pi)-pi; + } + return angle; +} + +double wrap_angle(const double &angle) { + double wrapped; + if ( ( angle <= pi ) && ( angle >= -pi ) ) { + wrapped = angle; + } else if ( angle < 0.0 ) { + wrapped = fmod(angle-pi,2.0*pi)+pi; + } else { + wrapped = fmod(angle+pi,2.0*pi)-pi; + } + return wrapped; +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline.cpp new file mode 100644 index 0000000..33e66b8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline.cpp @@ -0,0 +1,56 @@ +/** + * @file /src/lib/cubic_spline.cpp + * + * @brief Implementation for cubic splines. + * + * Implementation for cubic splines. + * + * @sa @ref splinesGeometry "Math::Splines. + * + * @date June 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/cubic_spline.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +double CubicSpline::operator()(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return cubic_polynomials[index](x); +} + +double CubicSpline::derivative(double x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return cubic_polynomials[index].derivative()(x); +} + +double CubicSpline::dderivative(double x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return cubic_polynomials[index].derivative().derivative()(x); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline_blueprints.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline_blueprints.cpp new file mode 100644 index 0000000..19c6b04 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/cubic_spline_blueprints.cpp @@ -0,0 +1,201 @@ +/** + * @file /src/lib/cubic_spline_blueprints.cpp + * + * @brief Implementation for cubic spline blueprints. + * + * Implementation for cubic spline blueprints. + * + * @sa @ref splinesGeometry "Math::Splines. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/geometry/cubic_spline.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace blueprints { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::OutOfRangeError; +using ecl::StandardException; + +/***************************************************************************** +** Implementation [C2CubicSpline] +*****************************************************************************/ +/* + * This algorithm can be found in page 115 of "Numerical Recipes in C" + * [The art of scientific computing] by Press, Vetterling, Tuekolsky, Flannery. + */ +C2CubicSpline::C2CubicSpline(const ecl::Array& x_set, const ecl::Array& y_set, + const double ydot_0, const double ydot_f) : + x_data(x_set), + y_data(y_set) +{ + if (x_data.size() < 2 || y_data.size() < 2) + { + ecl_throw(StandardException(LOC,OutOfRangeError) ); + } + ecl_assert_throw( x_data.size() == y_data.size(), StandardException(LOC,OutOfRangeError) ); + unsigned int n = x_data.size(); + yddot_data.resize(n); + Array u(n); // u is a temporary used in the algorithm + + // Initial boundary conditions + yddot_data[0] = -0.5; + u[0] = (3.0/(x_data[1]-x_data[0])) * ((y_data[1]-y_data[0])/(x_data[1]-x_data[0])-ydot_0); + // Set up the tridiagonal matrix to solve for the accelerations + for (unsigned int i = 1; i <= n-2; ++i){ + double sig = (x_data[i]-x_data[i-1]) / (x_data[i+1]-x_data[i-1]); + double p = sig*yddot_data[i-1]+2.0; + yddot_data[i] = (sig-1.0)/p; + u[i] = (y_data[i+1]-y_data[i])/(x_data[i+1]-x_data[i]) - + (y_data[i]-y_data[i-1])/(x_data[i]-x_data[i-1]); + u[i] = (6.0*u[i]/(x_data[i+1]-x_data[i-1]) - sig*u[i-1])/p; + } + // Final boundary conditions + double qn = 0.5; + u[n-1] = (3.0/(x_data[n-1]-x_data[n-2])) * (ydot_f - (y_data[n-1]-y_data[n-2])/(x_data[n-1]-x_data[n-2])); + + // Back substitution loop of the tridiagonal algorithm + yddot_data[n-1] = ( u[n-1] - qn*u[n-2]) / ( qn*yddot_data[n-2] + 1.0 ); + for ( int k = n-2; k >= 0; --k ) { + yddot_data[k] = yddot_data[k]*yddot_data[k+1] + u[k]; + } +} + +/* + * This is a special case of the above. You'll note that only initial and + * boundary conditions change here. + */ +C2CubicSpline::C2CubicSpline(const ecl::Array& x_set, const ecl::Array& y_set) : + x_data(x_set), + y_data(y_set) +{ + if (x_data.size() < 2 || y_data.size() < 2) + { + ecl_throw(StandardException(LOC,OutOfRangeError) ); + } + ecl_assert_throw( x_data.size() == y_data.size(), StandardException(LOC,OutOfRangeError) ); + unsigned int n = x_data.size(); + yddot_data.resize(n); + Array u(n); // u is a temporary used in the algorithm + + // Initial boundary conditions + yddot_data[0] = 0.0; + u[0] = 0.0; + // Set up the tridiagonal matrix to solve for the accelerations + for (unsigned int i = 1; i <= n-2; ++i){ + double sig = (x_data[i]-x_data[i-1]) / (x_data[i+1]-x_data[i-1]); + double p = sig*yddot_data[i-1]+2.0; + yddot_data[i] = (sig-1.0)/p; + u[i] = (y_data[i+1]-y_data[i])/(x_data[i+1]-x_data[i]) - + (y_data[i]-y_data[i-1])/(x_data[i]-x_data[i-1]); + u[i] = (6.0*u[i]/(x_data[i+1]-x_data[i-1]) - sig*u[i-1])/p; + } + // Final boundary conditions + double qn = 0.0; + u[n-1] = 0.0; + + // Back substitution loop of the tridiagonal algorithm + yddot_data[n-1] = ( u[n-1] - qn*u[n-2]) / ( qn*yddot_data[n-2] + 1.0 ); + for ( int k = n-2; k >= 0; --k ) { + yddot_data[k] = yddot_data[k]*yddot_data[k+1] + u[k]; + } +} + +ecl::CubicSpline C2CubicSpline::instantiate() { + CubicSpline cubic; + apply(cubic); + return cubic; +} + +void C2CubicSpline::apply(ecl::CubicSpline& spline) const { + + spline.discretised_domain = x_data; + spline.cubic_polynomials.resize(x_data.size()-1); // One less polynomials than there is points + for (unsigned int i = 0; i < spline.cubic_polynomials.size(); ++i ) { + spline.cubic_polynomials[i] = CubicPolynomial::SecondDerivativeInterpolation( + x_data[i], y_data[i], yddot_data[i], + x_data[i+1], y_data[i+1], yddot_data[i+1] ); + } +} + + +/***************************************************************************** +** Implementation [DerivativeHeuristicCubicSpline] +*****************************************************************************/ + +DerivativeHeuristicCubicSpline::DerivativeHeuristicCubicSpline(const ecl::Array& x_set, const ecl::Array& y_set, + const double ydot_0, const double ydot_f) : + x_data(x_set), + y_data(y_set) +{ + ecl_assert_throw( x_data.size() == y_data.size(), StandardException(LOC,OutOfRangeError) ); + /********************* + ** Via Velocities + **********************/ + ydot_data.resize(x_data.size()); + ydot_data[0] = ydot_0; + for (unsigned int i = 1; i < (x_data.size()-1); ++i ) { // Skip first and last. + double ydot_before, ydot_after; + ydot_before = (y_data[i]-y_data[i-1])/(x_data[i]-x_data[i-1]); + ydot_after = (y_data[i+1]-y_data[i])/(x_data[i+1]-x_data[i]); + ydot_data[i] = (ydot_before + ydot_after)/2; + } + ydot_data[x_data.size()-1] = ydot_f; +} + +ecl::CubicSpline DerivativeHeuristicCubicSpline::instantiate() { + CubicSpline cubic; + apply(cubic); + return cubic; +} + +void DerivativeHeuristicCubicSpline::apply(ecl::CubicSpline& spline) const { + + spline.discretised_domain = x_data; + spline.cubic_polynomials.resize(x_data.size()-1); // One less polynomials than there is points + for (unsigned int i = 0; i < spline.cubic_polynomials.size(); ++i ) { + spline.cubic_polynomials[i] = CubicPolynomial::DerivativeInterpolation( + x_data[i], y_data[i], ydot_data[i], + x_data[i+1], y_data[i+1], ydot_data[i+1] ); + } +} + +} // namespace blueprints + +/***************************************************************************** +** Implementation [BluePrintFactory][CubicSpline] +*****************************************************************************/ + +using blueprints::C2CubicSpline; +using blueprints::DerivativeHeuristicCubicSpline; + +C2CubicSpline BluePrintFactory< CubicSpline >::Natural(const Array& x_set, const Array& y_set) { + return C2CubicSpline(x_set, y_set); +} + + C2CubicSpline BluePrintFactory< CubicSpline >::ContinuousDerivatives( + const Array& x_set, const Array& y_set, const double ydot_0, const double ydot_f) { + return C2CubicSpline(x_set, y_set, ydot_0, ydot_f); +} + +DerivativeHeuristicCubicSpline BluePrintFactory< CubicSpline >::DerivativeHeuristic( + const Array& x_set, const Array& y_set, const double ydot_0, const double ydot_f) { + return DerivativeHeuristicCubicSpline(x_set, y_set, ydot_0, ydot_f); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/linear_segment.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/linear_segment.cpp new file mode 100644 index 0000000..f6f2a56 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/linear_segment.cpp @@ -0,0 +1,64 @@ +/** + * @file /ecl_geometry/src/lib/linear_segment.cpp + */ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/geometry/linear_segment.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +LinearSegment::LinearSegment(const double& x_1, + const double& y_1, + const double& x_2, + const double& y_2) +: x_1(x_1), y_1(y_1) +, x_2(x_2), y_2(y_2) +{ + if ( x_2 == x_1 ) { + B = 0; A = 1; C = x_1; + } else { + B = 1; + A = -1*(y_2-y_1)/(x_2-x_1); + C = -y_1 - x_1*A; + } +} + +double LinearSegment::squaredDistanceFromPoint(const double& x, const double& y) const +{ + // pp1 = [ x - x1 ] p2p1 = [ x2 - x1 ] + // [ y - y1 ] [ y2 - y1 ] + // The dot product of the above two vectors will give a hint as to where + // the point lies in relation to the segment + double dot = (x-x_1)*(x_2-x_1) + (y-y_1)*(y_2-y_1); + double squared_length_p2p1 = (x_2-x_1)*(x_2-x_1) + (y_2-y_1)*(y_2-y_1); + double t = -1; + if ( squared_length_p2p1 != 0 ) { // special case handling + t = dot / squared_length_p2p1; + } + double xx, yy; + if ( t < 0 ) { + xx = x_1; yy = y_1; + } else if ( t > 1 ) { + xx = x_2; yy = y_2; + } else { + xx = x_1 + t*(x_2-x_1); + yy = y_1 + t*(y_2-y_1); + } + return (x - xx)*(x - xx) + (y - yy)*(y - yy); +} + +/***************************************************************************** + ** Trailers + *****************************************************************************/ + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/odometry_helper.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/odometry_helper.cpp new file mode 100644 index 0000000..25e39c4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/odometry_helper.cpp @@ -0,0 +1,428 @@ +/** + * @file /src/lib/odometry_helper.cpp + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/odometry_helper.hpp" +#include "../../include/ecl/geometry/linear_segment.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace odometry { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +double distance(const Pose2D& pose, const Trajectory2D& trajectory) +{ + return distance(getPosition(pose), trajectory); +} + +double distance(const Position2D& position, const Trajectory2D& trajectory) +{ + Position2D segment_start = trajectory.topLeftCorner<2, 1>(); + + if (size(trajectory) == 1) + { + return (position - segment_start).norm(); + } + + double min_squared_distance = std::numeric_limits::infinity(); + double temp_squared_distance; + + for (int i = 1; i < size(trajectory); ++i) + { + Position2D segment_end = trajectory.block<2, 1>(0, i); + ecl::LinearSegment segment(getX(segment_start), getY(segment_start), getX(segment_end), getY(segment_end)); + + temp_squared_distance = segment.squaredDistanceFromPoint(getX(position), getY(position)); + + if (min_squared_distance > temp_squared_distance) + { + min_squared_distance = temp_squared_distance; + } + + segment_start = segment_end; + } + + return std::sqrt(min_squared_distance); +} + +bool empty(const Trajectory2D& trajectory) +{ + return size(trajectory) == 0; +} + +bool empty(const Odom2DTrajectory& trajectory) +{ + return size(trajectory) == 0; +} + +int size(const Trajectory2D& trajectory) +{ + return trajectory.cols(); +} + +int size(const Odom2DTrajectory& trajectory) +{ + return trajectory.cols(); +} + +double distance(const Odom2D& a, const Odom2D& b) +{ + return (getPosition(a) - getPosition(b)).norm(); +} + +double distance(const Pose2D& a, const Odom2D& b) +{ + return (getPosition(a) - getPosition(b)).norm(); +} + +double distance(const Pose2D& a, const Pose2D& b) +{ + return (getPosition(a) - getPosition(b)).norm(); +} + +double distanceSqared(const Odom2D& a, const Odom2D& b) +{ + return (getPosition(a) - getPosition(b)).squaredNorm(); +} + +double distanceSqared(const Pose2D& a, const Pose2D& b) +{ + return (getPosition(a) - getPosition(b)).squaredNorm(); +} + +void addAtEnd(Trajectory2D& target, const Trajectory2D& addition) +{ + if(size(target) == 0) + { + target = addition; + return; + } + + target << addition; +} + +void addAtEnd(Odom2DTrajectory& target, const Odom2DTrajectory& addition) +{ + if(size(target) == 0) + { + target = addition; + return; + } + + target << addition; +} + +Trajectory2D vectorToTrajectory(const std::vector& vec) +{ + Trajectory2D trajectory; + trajectory.resize(Eigen::NoChange, vec.size()); + + for (unsigned int i = 0; i < vec.size(); ++i) + { + setAt(trajectory, i, vec[i]); + } + + return trajectory; +} + +Odom2DTrajectory vectorToTrajectory(const std::vector& vec) +{ + Odom2DTrajectory trajectory; + trajectory.resize(Eigen::NoChange, vec.size()); + + for (unsigned int i = 0; i < vec.size(); ++i) + { + setAt(trajectory, i, vec[i]); + } + + return trajectory; +} + +void resize(Trajectory2D& trajectory, const int& size) +{ + trajectory.conservativeResize(Eigen::NoChange, size); +} + +void resize(Odom2DTrajectory& trajectory, const int& size) +{ + trajectory.conservativeResize(Eigen::NoChange, size); +} + +void setAt(Trajectory2D& trajectory, const int& index, const Pose2D& pose) +{ + trajectory.col(index) = pose; +} + +void setAt(Odom2DTrajectory& trajectory, const int& index, const Odom2D& odom) +{ + trajectory.col(index) = odom; +} + +Pose2D getAt(const Trajectory2D& trajectory, const int& index) +{ + return trajectory.col(index); +} + +Odom2D getAt(const Odom2DTrajectory& trajectory, const int& index) +{ + return trajectory.col(index); +} + +Pose2D getFront(const Trajectory2D& trajectory) +{ + return trajectory.leftCols<1>(); +} + +Pose2D getBack(const Trajectory2D& trajectory) +{ + return trajectory.rightCols<1>(); +} + +Odom2D getFront(const Odom2DTrajectory& trajectory) +{ + return trajectory.leftCols<1>(); +} + +Odom2D getBack(const Odom2DTrajectory& trajectory) +{ + return trajectory.rightCols<1>(); +} + +Trajectory2D getPoses(const Odom2DTrajectory& trajectory) +{ + return trajectory.topRows<3>(); +} + +Twist2DVector getTwists(const Odom2DTrajectory& trajectory) +{ + return trajectory.bottomRows<3>(); +} + +void setVelocityX(Odom2D& odom, const float& value) +{ + odom(3) = value; +} + +void setVelocityY(Odom2D& odom, const float& value) +{ + odom(4) = value; +} + +void setVelocityAngular(Odom2D& odom, const float& value) +{ + odom(5) = value; +} + +void setVelocityX(Twist2D& twist, const float& value) +{ + twist(0) = value; +} + +void setVelocityY(Twist2D& twist, const float& value) +{ + twist(1) = value; +} + +void setVelocityAngular(Twist2D& twist, const float& value) +{ + twist(2) = value; +} + +void setX(Odom2D& odom, const float& value) +{ + odom(0) = value; +} + +void setY(Odom2D& odom, const float& value) +{ + odom(1) = value; +} + +void setYaw(Odom2D& odom, const float& value) +{ + odom(2) = value; +} + +void setX(Pose2D& pose, const float& value) +{ + pose(0) = value; +} + +void setY(Pose2D& pose, const float& value) +{ + pose(1) = value; +} + +void setYaw(Pose2D& pose, const float& value) +{ + pose(2) = value; +} + +void setX(Position2D& position, const float& value) +{ + position(0) = value; +} + +void setY(Position2D& position, const float& value) +{ + position(1) = value; +} + +float getVelocityX(const Odom2D& odom) +{ + return getVelocityX(getTwist(odom)); +} + +float getVelocityY(const Odom2D& odom) +{ + return getVelocityY(getTwist(odom)); +} + +float getVelocityAngular(const Odom2D& odom) +{ + return getVelocityAngular(getTwist(odom)); +} + +float getVelocityX(const Twist2D& twist) +{ + return twist(0); +} + +float getVelocityY(const Twist2D& twist) +{ + return twist(1); +} + +float getVelocityAngular(const Twist2D& twist) +{ + return twist(2); +} + +float getX(const Odom2D& odom) +{ + return getX(getPose(odom)); +} +float getY(const Odom2D& odom) +{ + return getY(getPose(odom)); +} +float getYaw(const Odom2D& odom) +{ + return getYaw(getPose(odom)); +} + +Position2D getPosition(const Odom2D& odom) +{ + return getPosition(getPose(odom)); +} + +Pose2D getPose(const Odom2D& odom) +{ + return odom.head<3>(); +} + +Twist2D getTwist(const Odom2D& odom) +{ + return odom.tail<3>(); +} + +float getX(const Pose2D& pose) +{ + return getX(getPosition(pose)); +} + +float getY(const Pose2D& pose) +{ + return getY(getPosition(pose)); +} + +float getYaw(const Pose2D& pose) +{ + return pose(2); +} + +Position2D getPosition(const Pose2D& pose) +{ + return pose.head<2>(); +} + +float getX(const Position2D& position) +{ + return position(0); +} + +float getY(const Position2D& position) +{ + return position(1); +} + +/***************************************************************************** +** C++11 Implementations +*****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + + bool empty(const Trajectory2DPtr& trajectory_ptr) + { + return !trajectory_ptr || size(trajectory_ptr) == 0; + } + + bool empty(const Odom2DTrajectoryPtr& trajectory_ptr) + { + return !trajectory_ptr || size(trajectory_ptr) == 0; + } + + int size(const Trajectory2DPtr& trajectory) + { + return size(*trajectory); + } + + int size(const Odom2DTrajectoryPtr& trajectory) + { + return size(*trajectory); + } + + Trajectory2DPtr vectorToTrajectoryPtr(const std::vector& vec) + { + Trajectory2DPtr trajectory = std::make_shared(); + trajectory->resize(Eigen::NoChange, vec.size()); + + for (unsigned int i = 0; i < vec.size(); ++i) + { + setAt(*trajectory, i, vec[i]); + } + + return trajectory; + } + + Odom2DTrajectoryPtr vectorToTrajectoryPtr(const std::vector& vec) + { + Odom2DTrajectoryPtr trajectory = std::make_shared(); + trajectory->resize(Eigen::NoChange, vec.size()); + + for (unsigned int i = 0; i < vec.size(); ++i) + { + setAt(*trajectory, i, vec[i]); + } + + return trajectory; + } + +#endif /*ECL_CXX11_FOUND*/ + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace odometry +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pascals_triangle.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pascals_triangle.cpp new file mode 100644 index 0000000..0c805a4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pascals_triangle.cpp @@ -0,0 +1,77 @@ +/** + * @file /src/lib/pascals_triangle.cpp + * + * @brief Implementation of the pascal triangle specialisations. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/geometry/pascals_triangle.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [PascalsTriangle<3>] +*****************************************************************************/ +PascalsTriangle<3>::PascalsTriangle() { + coefficients << 1,1,1,1, + 1,2,3, + 1,3, + 1; +} + +PascalsTriangle<3>::const_iterator PascalsTriangle<3>::begin(unsigned int row_index) const { + int coeff_index = 0; + for (unsigned int i = 0; i < row_index; ++i ) { + coeff_index += 3+1-i; + } + return const_iterator( &coefficients[coeff_index] ); +} +PascalsTriangle<3>::const_iterator PascalsTriangle<3>::end(unsigned int row_index) const { + int coeff_index = 0; + for (unsigned int i = 0; i <= row_index; ++i ) { + coeff_index += 3+1-i; + } + coeff_index -= 1; // dont want to call beyond the array limit. + return const_iterator( (&coefficients[coeff_index])+1 ); +} + + +/***************************************************************************** +** Implementation [PascalsTriangle<5>] +*****************************************************************************/ +PascalsTriangle<5>::PascalsTriangle() { + coefficients << 1,1,1,1,1,1, + 1,2,3,4,5, + 1,3,6,10, + 1,4,10, + 1,5, + 1; +} + +PascalsTriangle<5>::const_iterator PascalsTriangle<5>::begin(unsigned int row_index) const { + int coeff_index = 0; + for (unsigned int i = 0; i < row_index; ++i ) { + coeff_index += 5+1-i; + } + return const_iterator( &coefficients[coeff_index] ); +} +PascalsTriangle<5>::const_iterator PascalsTriangle<5>::end(unsigned int row_index) const { + int coeff_index = 0; + for (unsigned int i = 0; i <= row_index; ++i ) { + coeff_index += 5+1-i; + } + coeff_index -= 1; // dont want to call beyond the array limit. + return const_iterator( (&coefficients[coeff_index])+1 ); +} + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial.cpp new file mode 100644 index 0000000..bc64d2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial.cpp @@ -0,0 +1,274 @@ +/** + * @file /src/lib/polynomial.cpp + * + * @brief Implementation of the polynomials. + * + * Implementation of the polynomials. + * + * @author Daniel J. Stonier + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +//#include +#include +#include +#include +#include // cube_root +#include "../../include/ecl/geometry/polynomial.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Synthetic Division] +*****************************************************************************/ + +LinearFunction Division< QuadraticPolynomial >::operator()(const QuadraticPolynomial &p, const double &factor, double &remainder) { + double a, b; // linear coefficients + a = p.coefficients()[2]; + b = p.coefficients()[1] + factor*a; + LinearFunction f; + f.coefficients() << b, a; + remainder = p.coefficients()[0]+factor*b; + return f; +} + +QuadraticPolynomial Division< CubicPolynomial >::operator()(const CubicPolynomial &p, const double &factor, double &remainder) { + double a, b, c; // quadratic coefficients + a = p.coefficients()[3]; + b = p.coefficients()[2] + factor*a; + c = p.coefficients()[1] + factor*b; + QuadraticPolynomial q; + q.coefficients() << c, b, a; + remainder = p.coefficients()[0]+factor*c; + return q; +} + +/***************************************************************************** +** Implementation [Minimum|Maximum][Polynomial] +*****************************************************************************/ + +Array Roots< LinearFunction >::operator()(const LinearFunction& p) { + Array intercepts; + double a = p.coefficients()[1]; + double b = p.coefficients()[0]; + if ( a != 0 ) { + intercepts.resize(1); + intercepts << -1.0*b/a; + } + return intercepts; +} + +Array Roots< QuadraticPolynomial >::operator()(const QuadraticPolynomial& p) { + Array intercepts; + double a = p.coefficients()[2]; + double b = p.coefficients()[1]; + double c = p.coefficients()[0]; + if ( a == 0 ) { + LinearFunction f; + f.coefficients() << c, b; + intercepts = Roots()(f); + } else { + double discriminant = b*b - 4*a*c; + if ( discriminant > 0.0 ) { + intercepts.resize(2); + intercepts << (-b + sqrt(discriminant))/(2*a), (-b - sqrt(discriminant))/(2*a); + } else if ( discriminant == 0.0 ) { + intercepts.resize(1); + intercepts << -b/(2*a); + } + } + return intercepts; +} + + // http://en.wikipedia.org/wiki/Cubic_function#Roots_of_a_cubic_function +Array Roots< CubicPolynomial >::operator()(const CubicPolynomial& polynomial) { + Array intercepts; + double a = polynomial.coefficients()[3]; + double b = polynomial.coefficients()[2]; + double c = polynomial.coefficients()[1]; + double d = polynomial.coefficients()[0]; + +// form the companion matrix (http://stackoverflow.com/questions/2003465/fastest-numerical-solution-of-a-real-cubic-polynomial) +// ecl::linear_algebra::Matrix3d A; +// A << 0, 0, -d/a, 1, 0, -c/a, 0, 1, -b/a; +// ecl::linear_algebra::EigenSolver eigensolver(A); +// if (eigensolver.info() != ecl::linear_algebra::Success) abort(); +// cout << "The eigenvalues of A are:\n" << eigensolver.eigenvalues() << endl; + + // Monic Trinomial coefficients + double p = (3*a*c - b*b)/(3*a*a); + double q = (2*b*b*b - 9*a*b*c + 27*a*a*d)/(27*a*a*a); + double discriminant = p*p*p/27 + q*q/4; +// std::cout << "p: " << p << std::endl; +// std::cout << "q: " << q << std::endl; + // using transform x = t - b/3a, we can solve t^3+pt+q=0 + double shift = -b/(3*a); + if ( ( p == 0 ) && ( q == 0 ) ) { + // single, triple root at t = 0 + intercepts.resize(1); + intercepts << shift; +// std::cout << "Single triple root" << std::endl; + } else if ( p == 0 ) { // && ( q != 0 ) + // single root from the cube root function +// std::cout << "Single root from cube root function" << std::endl; + intercepts.resize(1); + intercepts << ecl::cube_root(-q)+ shift; + } else if ( q == 0 ) { +// std::cout << "Three real roots" << std::endl; + // three real roots + intercepts.resize(3); + intercepts << shift, sqrt(-1*p) + shift, -sqrt(-1*p) + shift; + } else if ( discriminant == 0 ) { // && ( p != 0 ) ) { +// std::cout << "Double root" << std::endl; +// // double root and simple root + intercepts.resize(2); + intercepts << 3*q/p + shift, (-3*q)/(2*p) + shift; + } else if ( discriminant >= 0 ) { +// std::cout << "Discriminant: " << discriminant << std::endl; + double u = ecl::cube_root(-q/2 + sqrt(discriminant)); + double v = ecl::cube_root(-q/2 - sqrt(discriminant)); + intercepts.resize(1); + intercepts << u + v + shift; + } else { // discriminant < 0 this is cardano's casus irreducibilis and there is three real roots + // switch to transcendental solutions (only works for three real roots) + // http://en.wikipedia.org/wiki/Cubic_function#Trigonometric_.28and_hyperbolic.29_method +// std::cout << "Discriminant: " << discriminant << std::endl; + double t_1 = 2.0*sqrt(-p/3.0)*cos((1.0/3.0)*acos( ((3.0*q)/(2.0*p)) * sqrt(-3.0/p))); + double t_2 = 2.0*sqrt(-p/3.0)*cos((1.0/3.0)*acos(( (3.0*q)/(2.0*p)) * sqrt(-3.0/p))-(2.0*ecl::pi)/3.0); + double t_3 = 2.0*sqrt(-p/3.0)*cos((1.0/3.0)*acos(( (3.0*q)/(2.0*p)) * sqrt(-3.0/p))-(4.0*ecl::pi)/3.0); + intercepts.resize(3); + intercepts << t_1+shift, t_2+shift, t_3+shift; + } + return intercepts; +} + +CartesianPoint2d Intersection< LinearFunction >::operator()(const LinearFunction &f, const LinearFunction &g) { + CartesianPoint2d point; + double a_0 = f.coefficients()[0]; + double b_0 = f.coefficients()[1]; + double a_1 = g.coefficients()[0]; + double b_1 = g.coefficients()[1]; + if ( isApprox(b_0, b_1) ) { // should use some epsilon distance here. + last_operation_failed = true; + ecl_throw(StandardException(LOC,OutOfRangeError,"Functions are collinear, no intersection possible.")); + } else { + point.x((a_0 - a_1)/(b_1 - b_0)); + point.y(f(point.x())); + } + return point; +} + +double Maximum< LinearFunction >::operator()( + const double& x_begin, const double& x_end, const LinearFunction &function) { + double max = function(x_begin); + double test_max = function(x_end); + if ( test_max > max ) { + max = test_max; + } + return max; +} + +double Maximum::operator()( + const double& x_begin, const double& x_end, const CubicPolynomial& cubic) { + // 3a_3x^2 + 2a_2x + a_1 = 0 + double max = cubic(x_begin); + double test_max = cubic(x_end); + if ( test_max > max ) { + max = test_max; + } + CubicPolynomial::Coefficients coefficients = cubic.coefficients(); + double a = 3*coefficients[3]; + double b = 2*coefficients[2]; + double c = coefficients[1]; + if ( a == 0 ) { + double root = -c/b; + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_max = cubic(root); + if ( test_max > max ) { + max = test_max; + } + } + } else { + double sqrt_term = b*b-4*a*c; + if ( sqrt_term > 0 ) { + double root = ( -b + sqrt(b*b-4*a*c))/(2*a); + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_max = cubic(root); + if ( test_max > max ) { + max = test_max; + } + } + root = ( -b - sqrt(b*b-4*a*c))/(2*a); + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_max = cubic(root); + if ( test_max > max ) { + max = test_max; + } + } + } + } + return max; +} + +double Minimum< LinearFunction >::operator()( + const double& x_begin, const double& x_end, const LinearFunction &function) { + double min = function(x_begin); + double test_min = function(x_end); + if ( test_min < min ) { + min = test_min; + } + return min; +} + +double Minimum::operator()( + const double& x_begin, const double& x_end, const CubicPolynomial& cubic) { + // 3a_3x^2 + 2a_2x + a_1 = 0 + double min = cubic(x_begin); + double test_min = cubic(x_end); + if ( test_min < min ) { + min = test_min; + } + CubicPolynomial::Coefficients coefficients = cubic.coefficients(); + double a = 3*coefficients[3]; + double b = 2*coefficients[2]; + double c = coefficients[1]; + if ( a == 0 ) { + double root = -c/b; + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_min = cubic(root); + if ( test_min < min ) { + min = test_min; + } + } + } else { + double sqrt_term = b*b-4*a*c; + if ( sqrt_term > 0 ) { + double root = ( -b + sqrt(b*b-4*a*c))/(2*a); + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_min = cubic(root); + if ( test_min < min ) { + min = test_min; + } + } + root = ( -b - sqrt(b*b-4*a*c))/(2*a); + if ( ( root > x_begin ) && ( root < x_end ) ) { + test_min = cubic(root); + if ( test_min < min ) { + min = test_min; + } + } + } + } + return min; +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial_blueprints.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial_blueprints.cpp new file mode 100644 index 0000000..184b88f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/polynomial_blueprints.cpp @@ -0,0 +1,231 @@ +/** + * @file /src/lib/polynomial_blueprints.cpp + * + * @brief Implementation of the polynomial blueprints. + * + * Implementation of the polynomial blueprints. + * + * @sa @ref polynomialsGeometry "Math::Polynomials". + * + * @author Daniel J. Stonier + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/geometry/polynomial.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace blueprints { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::LinearFunction; +using ecl::CubicPolynomial; +using ecl::QuinticPolynomial; + +/***************************************************************************** +** Implementation [LinearInterpolation][LinearPointSlopeForm] +*****************************************************************************/ + +ecl::LinearFunction LinearInterpolation::instantiate() { + LinearFunction function; + apply(function); + return function; +} + +void LinearInterpolation::apply(ecl::LinearFunction& function) const { + LinearFunction::Coefficients &coefficients = function.coefficients(); + // First compute the polynomial on [0,xf-xi] (this is easier), then shift it. + + // y = a_1 x + a_0 + double a_1 = (y_final-y_initial)/(x_final-x_initial); + double a_0 = y_initial - a_1*x_initial; + + coefficients << a_0, a_1; +} + +ecl::LinearFunction LinearPointSlopeForm::instantiate() { + LinearFunction function; + apply(function); + return function; +} + +void LinearPointSlopeForm::apply(ecl::LinearFunction& function) const { + LinearFunction::Coefficients &coefficients = function.coefficients(); + // First compute the polynomial on [0,xf-xi] (this is easier), then shift it. + + // y = a_1 x + a_0 + double a_1 = slope; + double a_0 = y_final - a_1*x_final; + + coefficients << a_0, a_1; +} + + +/***************************************************************************** +** Implementation [CubicDerivativeInterpolation] +*****************************************************************************/ + + +ecl::CubicPolynomial CubicDerivativeInterpolation::instantiate() { + CubicPolynomial cubic; + apply(cubic); + return cubic; +} + +void CubicDerivativeInterpolation::apply(ecl::CubicPolynomial& polynomial) const { + Polynomial<3>::Coefficients &coefficients = polynomial.coefficients(); + // First compute the polynomial on [0,xf-xi] (this is easier), then shift it. + double dx = x_final - x_initial; + double dy = y_final - y_initial; + coefficients << y_initial, + ydot_initial, + (3/(dx*dx))*(dy) - (2/dx)*ydot_initial - (1/dx)*ydot_final, + (-2/(dx*dx*dx))*(dy) + (ydot_final + ydot_initial)/(dx*dx); + +// Matrix A; +// Matrix a,b; +// b << y_initial, ydot_initial, y_final, ydot_final; +// +// A << 1, 0, 0, 0, +// 0, 1, 0, 0, +// 1, dx, dx*dx, dx*dx*dx, +// 0, 1, 2*dx, 3*dx*dx; +// +// a = A.inverse()*b; +// std::cout << coefficients << std::endl; +// std::cout << a << std::endl; + + if ( x_initial != 0.0 ) { + polynomial.shift_horizontal(x_initial); + } +} + +/***************************************************************************** +** Implementation [CubicDerivativeInterpolation] +*****************************************************************************/ + +ecl::CubicPolynomial CubicSecondDerivativeInterpolation::instantiate() { + CubicPolynomial cubic; + apply(cubic); + return cubic; +} + +void CubicSecondDerivativeInterpolation::apply(ecl::CubicPolynomial& polynomial) const { + Polynomial<3>::Coefficients &coefficients = polynomial.coefficients(); + // First compute the polynomial on [0,xf-xi] (this is easier), then shift it. + double dx = x_final - x_initial; + double a_0 = y_initial; + double a_2 = yddot_initial/2; + double a_3 = (yddot_final - yddot_initial)/(6*dx); + double a_1 = (y_final-a_0-a_2*dx*dx - a_3*dx*dx*dx)/dx; + coefficients << a_0, a_1, a_2, a_3; + if ( x_initial != 0.0 ) { + polynomial.shift_horizontal(x_initial); + } +} + +/***************************************************************************** +** Implementation [QuinticInterpolation] +*****************************************************************************/ + +ecl::QuinticPolynomial QuinticInterpolation::instantiate() { + QuinticPolynomial quintic; + apply(quintic); + return quintic; +} + +void QuinticInterpolation::apply(ecl::QuinticPolynomial& polynomial) const { + QuinticPolynomial::Coefficients &coefficients = polynomial.coefficients(); + // First compute the polynomial on [0,xf-xi] (this is easier), then shift it. + + double dx = x_final - x_initial; + double d2x = dx*dx; + double d3x = d2x*dx; + double d4x = d3x*dx; + double d5x = d4x*dx; + double a_0 = y_initial; + double a_1 = ydot_initial; + double a_2 = yddot_initial/2; + double a_3 = ( 20*(y_final - y_initial) - (8*ydot_final + 12*ydot_initial)*dx - (3*yddot_initial - yddot_final)*dx*dx ) + / (2*d3x); + double a_4 = ( 30*(y_initial - y_final) + (14*ydot_final + 16*ydot_initial)*dx + (- 2*yddot_final + 3*yddot_initial)*dx*dx ) + / (2*d4x); + double a_5 = ( 12*(y_final - y_initial) - (6*ydot_final + 6*ydot_initial)*dx - (yddot_initial - yddot_final)*dx*dx ) + / (2*d5x); + + coefficients << a_0, a_1, a_2, a_3, a_4, a_5; + +// Matrix A; +// Matrix a,b; +// b << y_initial, ydot_initial, yddot_initial, y_final, ydot_final, yddot_final; +// +// A << 1, 0, 0, 0, 0, 0, +// 0, 1, 0, 0, 0, 0, +// 0, 0, 2, 0, 0, 0, +// 1, dx, d2x, d3x, d4x, d5x, +// 0, 1, 2*dx, 3*d2x, 4*d3x, 5*d4x, +// 0, 0, 2, 6*dx, 12*d2x, 20*d3x; +// +// a = A.inverse()*b; +// std::cout << coefficients << std::endl; +// std::cout << a << std::endl; + + if ( x_initial != 0.0 ) { + polynomial.shift_horizontal(x_initial); + } +} + + +} // namespace blueprints + +using blueprints::LinearInterpolation; +using blueprints::LinearPointSlopeForm; +using blueprints::CubicDerivativeInterpolation; +using blueprints::CubicSecondDerivativeInterpolation; +using blueprints::QuinticInterpolation; + +/***************************************************************************** +** BluePrintFactory[LinearFunction] +*****************************************************************************/ + +LinearInterpolation BluePrintFactory< LinearFunction >::Interpolation(const double x_i, const double y_i, const double x_f, const double y_f) { + return LinearInterpolation(x_i, y_i, x_f, y_f); +} + +LinearPointSlopeForm BluePrintFactory< LinearFunction >::PointSlopeForm(const double x_f, const double y_f, const double slope) { + return LinearPointSlopeForm(x_f, y_f, slope); +} + +/***************************************************************************** +** BluePrintFactory[CubicPolynomial] +*****************************************************************************/ + +CubicDerivativeInterpolation BluePrintFactory< CubicPolynomial >::DerivativeInterpolation(const double x_i, const double y_i, const double ydot_i, const double x_f, const double y_f, const double ydot_f) { + return CubicDerivativeInterpolation(x_i, y_i, ydot_i, x_f, y_f, ydot_f); +} + +CubicSecondDerivativeInterpolation BluePrintFactory< CubicPolynomial >::SecondDerivativeInterpolation(const double x_i, const double y_i, const double yddot_i, const double x_f, const double y_f, const double yddot_f) { + return CubicSecondDerivativeInterpolation(x_i, y_i, yddot_i, x_f, y_f, yddot_f); +} + +/***************************************************************************** +** BluePrintFactory[QuinticPolynomial] +*****************************************************************************/ + +QuinticInterpolation BluePrintFactory< QuinticPolynomial >::Interpolation(const double x_i, const double y_i, const double ydot_i, const double yddot_i, + const double x_f, const double y_f, const double ydot_f, const double yddot_f) { + return QuinticInterpolation(x_i, y_i, ydot_i, yddot_i, x_f, y_f, ydot_f, yddot_f); +} + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pose2d.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pose2d.cpp new file mode 100644 index 0000000..8dfe478 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/pose2d.cpp @@ -0,0 +1,25 @@ +/** + * @file /src/lib/pose.cpp + * + * @brief Implementation of the pose library suite. + * + * Implementation of the pose library suite. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +#include "../../include/ecl/geometry/pose2d.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace pose2d { + +} // namespace pose2d +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/smooth_linear_spline.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/smooth_linear_spline.cpp new file mode 100644 index 0000000..fec1839 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/smooth_linear_spline.cpp @@ -0,0 +1,155 @@ +/** + * @file /src/lib/smooth_linear_spline.cpp + * + * @brief Implementation for ramped splines. + * + * Implementation for ramped splines. + * + * @date July 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/smooth_linear_spline.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +SmoothLinearSpline::SmoothLinearSpline(const Array& x_data, const Array& y_data, double a_max) { + + if ( x_data.size() != y_data.size() ) { + throw DataException(LOC,OutOfRangeError,"Input domain and range sets were not the same size.", 0); + } + + /********************* + ** Basic Parameters + **********************/ + // n = number of linear segments + // 2*n = number of points (2 end points + 2*(n-1) corners) remember we're including the polynomial corners in this calculation + unsigned int n = x_data.size()-1; + + /****************************************** + ** Storage + *******************************************/ + segments.resize(n); + corners.resize(n-1); + discretised_domain.resize(2*n); + + /****************************************** + ** Build Segments + *******************************************/ + for ( unsigned int i = 0; i < n; ++i ) { + segments[i] = LinearFunction::Interpolation(x_data[i],y_data[i],x_data[i+1],y_data[i+1]); + } + discretised_domain[0] = x_data[0]; // Initial point + discretised_domain[2*n-1] = x_data[n]; // Last point + + /****************************************** + ** Build Corners (this might throw) + *******************************************/ + for ( unsigned int i = 1; i < n; ++i ) { + if ( segments[i-1].coefficients()[1] == segments[i].coefficients()[1] ) { // slope identical + // Just set the quintic to be a linear function. + corners[i-1].coefficients() << segments[i-1].coefficients()[0], segments[i-1].coefficients()[1], 0.0, 0.0, 0.0, 0.0; + discretised_domain[1+2*(i-1)] = x_data[i]; + discretised_domain[1+2*(i-1)+1] = x_data[i]; + } else { + for ( unsigned int j = 1; j <= 5; ++j ) { + double x_l, x_r; + if ( i == 1 ) { // First one, we can use the whole segment + x_l = x_data[i] - j*(x_data[i]-x_data[i-1])/5; + } else { + x_l = x_data[i] - j*(x_data[i]-x_data[i-1])/10; + } + if ( i == (n-1) ) { // Last one, we can use the whole segment + x_r = x_data[i] + j*(x_data[i+1]-x_data[i])/5; + } else { + x_r = x_data[i] + j*(x_data[i+1]-x_data[i])/10; + } + double y_l = segments[i-1](x_l); + double y_r = segments[i](x_r); + double ydot_l = segments[i-1].derivative(x_l); + double ydot_r = segments[i].derivative(x_r); + corners[i-1] = QuinticPolynomial::Interpolation(x_l,y_l,ydot_l,0.0, + x_r,y_r,ydot_r,0.0); + if ( ( fabs( Maximum()(x_l,x_r,corners[i-1].derivative().derivative())) < fabs(a_max) ) && + ( fabs( Minimum()(x_l,x_r,corners[i-1].derivative().derivative())) < fabs(a_max) ) ) { + discretised_domain[1+2*(i-1)] = x_l; + discretised_domain[1+2*(i-1)+1] = x_r; + break; + } + /********************* + ** Debugging + **********************/ +// if ( i == 1 ) { +// double max = fabs( Maximum()(x_l,x_r,corners[i-1].derivative().derivative())); +// if ( fabs( Minimum()(x_l,x_r,corners[i-1].derivative().derivative())) > max ) { +// max = fabs( Minimum()(x_l,x_r,corners[i-1].derivative().derivative())); +// } +// std::cout << "Max: " << max << std::endl; +// } + + if ( j == 5 ) { // Cannot exceed more than half the length of the segment. + throw DataException(LOC,ConstructorError,"Max acceleration bound could not be satisfied at corner specified by the data element.",i); + } + } + } + } +} + +double SmoothLinearSpline::operator()(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + if ( index % 2 == 0 ) { // linear + return segments[index/2](x); + } else { // quintic + return corners[(index-1)/2](x); + } +} + +double SmoothLinearSpline::derivative(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + if ( index % 2 == 0 ) { // linear + return segments[index/2].derivative(x); + } else { // quintic + return corners[(index-1)/2].derivative(x); + } +} + +double SmoothLinearSpline::dderivative(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + if ( index % 2 == 0 ) { // linear + return segments[index/2].dderivative(x); + } else { // quintic + return corners[(index-1)/2].dderivative(x); + } +} + +} // namespace ecl + + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_function.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_function.cpp new file mode 100644 index 0000000..136213d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_function.cpp @@ -0,0 +1,91 @@ +/** + * @file /src/lib/tension_function.cpp + * + * @brief Implementation of the tension function. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/tension_function.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [TensionFunction] +*****************************************************************************/ + +double TensionFunction::derivative(const double &tau, const double &x) const { + double value; + double h = x_f-x_0; + value = (-1.0*tau*z_0*cosh(tau*(x_f-x)) + tau*z_f*cosh(tau*(x-x_0)))/(tau*tau*sinh(tau*h)); + value += -1.0*(y_0-z_0/(tau*tau))/h; + value += (y_f-z_f/(tau*tau))/h; + + return value; +} + + +double TensionFunction::dderivative(const double &tau, const double &x) const { + double value; + double h = x_f-x_0; + value = (tau*tau*z_0*sinh(tau*(x_f-x)) + tau*tau*z_f*sinh(tau*(x-x_0)))/(tau*tau*sinh(tau*h)); + + return value; +} + +double TensionFunction::operator ()(const double &tau, const double &x) const { + double value; + double h = x_f-x_0; + value = (z_0*sinh(tau*(x_f-x)) + z_f*sinh(tau*(x-x_0)))/(tau*tau*sinh(tau*h)); + value += (y_0-z_0/(tau*tau))*(x_f-x)/h; + value += (y_f-z_f/(tau*tau))*(x-x_0)/h; + return value; +} + +namespace blueprints { + +using ecl::TensionFunction; + +/***************************************************************************** +** Implementation [TensionSecondDerivativeInterpolation] +*****************************************************************************/ + +ecl::TensionFunction TensionSecondDerivativeInterpolation::instantiate() { + TensionFunction function; + apply(function); + return function; +} + +void TensionSecondDerivativeInterpolation::apply(base_type &function) const { + + // Dont have to do much here, just copy across the parameters + function.z_0 = yddot_initial; + function.z_f = yddot_final; + function.x_0 = x_initial; + function.x_f = x_final; + function.y_0 = y_initial; + function.y_f = y_final; +} + +} // namespace blueprints + +using blueprints::TensionSecondDerivativeInterpolation; + +/***************************************************************************** +** BluePrintFactory[TensionFunction] +*****************************************************************************/ + +TensionSecondDerivativeInterpolation BluePrintFactory< TensionFunction >::Interpolation(const double x_i, const double y_i, const double yddot_i, const double x_f, const double y_f, const double yddot_f) { + return TensionSecondDerivativeInterpolation(x_i, y_i, yddot_i, x_f, y_f, yddot_f); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline.cpp new file mode 100644 index 0000000..388872f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline.cpp @@ -0,0 +1,56 @@ +/** + * @file /src/lib/tension_spline.cpp + * + * @brief Implementation for tension splines. + * + * Implementation for tension splines. + * + * @sa @ref splinesGeometry "Math::Splines. + * + * @author Daniel J. Stonier + * @date 20/05/2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/geometry/tension_spline.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +double TensionSpline::operator()(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return functions[index](tension,x); +} + +double TensionSpline::derivative(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return functions[index].derivative(tension,x); +} + +double TensionSpline::dderivative(const double &x) const { + ecl_assert_throw( ( ( x >= discretised_domain.front() ) && ( x <= discretised_domain.back() ) ), StandardException(LOC,OutOfRangeError) ); + int index = 0; + while ( x > discretised_domain[index+1] ) { + ++index; + } + return functions[index].dderivative(tension,x); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline_blueprints.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline_blueprints.cpp new file mode 100644 index 0000000..ed11de8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/lib/tension_spline_blueprints.cpp @@ -0,0 +1,130 @@ +/** + * @file /src/lib/tension_spline_blueprints.cpp + * + * @brief Implementation for tension spline blueprints. + * + * @sa @ref splinesGeometry "Math::Splines. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/tension_spline.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace blueprints { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::OutOfRangeError; +using ecl::StandardException; + +/***************************************************************************** +** Implementation [C2CubicSpline] +*****************************************************************************/ +/* + * This algorithm can be found on page 323 of "Numerical Analysis" [Kincaid & + * Cheney]. + */ +C2TensionSpline::C2TensionSpline(const ecl::Array& x_set, const ecl::Array& y_set, + const double &tau) : + x_data(x_set), + y_data(y_set) +{ + ecl_assert_throw( x_data.size() == y_data.size(), StandardException(LOC,OutOfRangeError) ); + + /********************* + ** Basic Parameters + **********************/ + unsigned int n = x_data.size()-1; // No. of data points (x_0...x_n) + yddot_data.resize(n+1); + yddot_data[0] = 0; + tension = tau; + + /****************************************** + ** Tridiagonal parameters + *******************************************/ + // These equations are derived from the c2 constraints - it results in a tridiagonal system + // of equations. See p.319 of kincaid and cheney for the tridiagonal solution (note this + // is only valid for diagonally dominant tridiagonal matrices! Is this a problem for us? + Array h(n), a(n), beta(n), gamma(n), u(n), v(n); + h[0] = x_set[1] - x_set[0]; + for ( unsigned int i = 0; i < n; ++i ) { + h[i] = x_set[i+1]-x_set[i]; + a[i] = 1/h[i] - tension/sinh(tension*h[i]); + beta[i] = tension*(cosh(tension*h[i])/sinh(tension*h[i])) - 1/h[i]; + gamma[i] = tension*tension*(y_data[i+1]-y_data[i])/h[i]; + } + /* + * [ u1 a1 0 0 0 ] [z1] [ v1 ] + * [ a1 u2 a2 0 0 ] [z2] [ v2 ] + * [ 0 a2 u3 a3 0 ] [z3] [ v3 ] + * + * but with back substitution here, + * + * [ u1 a1 0 0 0 ] [z1] [ v1 ] + * [ 0 (u2-a1^2/u1) a2 0 0 ] [z2] [ v2-a1*v1/u1 ] + * + * etc + */ + u[1] = beta[1] + beta[0]; + v[1] = gamma[1]-gamma[0]; + for ( unsigned int i = 2; i < n; ++i ) { + u[i] = beta[i] + beta[i-1] - a[i-1]*a[i-1]/u[i-1]; + v[i] = gamma[i]-gamma[i-1] - a[i-1]*v[i-1]/u[i-1]; + } + /* + * Now we can roll the upper triangular matrix backwards + */ + yddot_data[n] = 0; + for ( unsigned int i = n-1; i > 0; --i ) { + yddot_data[i] = (v[i] - a[i]*yddot_data[i+1])/u[i]; + } + yddot_data[0] = 0; +} + +TensionSpline C2TensionSpline::instantiate() { + TensionSpline cubic; + apply(cubic); + return cubic; +} + +void C2TensionSpline::apply(TensionSpline& spline) const { + + spline.discretised_domain = x_data; + spline.tension = tension; + spline.functions.resize(x_data.size()-1); // One less polynomials than there is points + for (unsigned int i = 0; i < spline.functions.size(); ++i ) { + spline.functions[i] = TensionFunction::Interpolation( + x_data[i], y_data[i], yddot_data[i], + x_data[i+1], y_data[i+1], yddot_data[i+1] ); + } +} + +} // namespace blueprints + +/***************************************************************************** +** Implementation [BluePrintFactory][TensionSpline] +*****************************************************************************/ + +using blueprints::C2TensionSpline; + + +C2TensionSpline BluePrintFactory< TensionSpline >::Natural(const Array& x_set, + const Array& y_set, const double &tau) { + return C2TensionSpline(x_set, y_set, tau); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_geometry/src/test/CMakeLists.txt new file mode 100644 index 0000000..3193771 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/CMakeLists.txt @@ -0,0 +1,39 @@ +############################################################################### +# GTest setup +############################################################################### + +macro(ecl_geometry_add_gtest TESTNAME) + ament_add_gtest(ecl_test_${TESTNAME} ${TESTNAME}.cpp) + if(TARGET ecl_test_${TESTNAME}) + target_link_libraries( + ecl_test_${TESTNAME} + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_containers::ecl_containers + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_linear_algebra::ecl_linear_algebra + ecl_math::ecl_math + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits + ) + endif() +endmacro(ecl_geometry_add_gtest) + +############################################################################### +# GTests +############################################################################### + +ecl_geometry_add_gtest(angles) +ecl_geometry_add_gtest(cartesian_points) +ecl_geometry_add_gtest(cubic_splines) +ecl_geometry_add_gtest(homogeneous_points) +ecl_geometry_add_gtest(legacy_pose2d) +ecl_geometry_add_gtest(legacy_pose3d) +ecl_geometry_add_gtest(linear_segment) +ecl_geometry_add_gtest(polynomials) +ecl_geometry_add_gtest(pose2d) +ecl_geometry_add_gtest(smooth_linear_splines) +ecl_geometry_add_gtest(tension_function) +ecl_geometry_add_gtest(tension_splines) +ecl_geometry_add_gtest(odometry_helper) diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/angles.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/angles.cpp new file mode 100644 index 0000000..d7a7268 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/angles.cpp @@ -0,0 +1,109 @@ +/** + * @file /src/test/angles.cpp + * + * @ingroup UnitTests + * + * Use this to test the angle classes. + * + * @date February 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/geometry/angle.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::pi; +using ecl::Angle; +using ecl::wrap_angle; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(AngleTests,setters) { + Angle angle; + double d = angle; // default + EXPECT_EQ(0.0,d); + angle = Angle::Degrees(45.0); + d = angle; + EXPECT_GT(0.786,d); // Allow some roundoff error here + EXPECT_LT(0.785,d); + angle = Angle::Radians(0.3); + d = angle; + EXPECT_EQ(0.3,d); + Angle angle_f; + float f = angle_f; // default + EXPECT_EQ(0.0,f); + angle_f = Angle::Degrees(45.0); + f = angle_f; + EXPECT_GT(0.786,f); // Allow some roundoff error here + EXPECT_LT(0.785,f); + angle_f = Angle::Radians(0.3); + f = angle_f; + EXPECT_EQ(0.3f,f); +} + +TEST(AngleTests,conversions) { + Angle angle(0.3); + double d = angle.degrees(); + EXPECT_GT(17.19,d); // Allow some roundoff error here + EXPECT_LT(17.18,d); + Angle angle_f(0.3); + float f = angle.degrees(); + EXPECT_GT(17.19,f); // Allow some roundoff error here + EXPECT_LT(17.18,f); +} + +TEST(AngleTests,wrap) { + double angle = 2*pi+0.1; + wrap_angle(angle); + EXPECT_GT(0.11,angle); // Allow some roundoff error here + EXPECT_LT(0.09,angle); + angle = 2*pi+0.1; + double wa = wrap_angle(angle); + EXPECT_GT(0.11,wa); // Allow some roundoff error here + EXPECT_LT(0.09,wa); + float angle_f = 2*pi+0.1; + wrap_angle(angle_f); + EXPECT_GT(0.11,angle_f); // Allow some roundoff error here + EXPECT_LT(0.09,angle_f); + angle_f = 2*pi+0.1; + float wa_f = wrap_angle(angle_f); + EXPECT_GT(0.11,wa_f); // Allow some roundoff error here + EXPECT_LT(0.09,wa_f); +} + +TEST(AngleTests,assignment) { + Angle angle; + angle = 0.3; + double d = angle; + EXPECT_GT(0.31,d); // Allow some roundoff error here + EXPECT_LT(0.29,d); + Angle angle_f; + angle_f = 0.3; + float f = angle_f; + EXPECT_GT(0.31,f); // Allow some roundoff error here + EXPECT_LT(0.29,f); +} + +// operator tests + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/cartesian_points.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/cartesian_points.cpp new file mode 100644 index 0000000..3ad34dd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/cartesian_points.cpp @@ -0,0 +1,89 @@ +/** + * @file /src/test/cartesian_points.cpp + * + * @brief Unit Test for the cartesian point classes. + * + * @date October 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/cartesian_point.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::linear_algebra::Vector3d; +using ecl::CartesianPoint; +using ecl::CartesianPoint3d; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(CartesianPointTests,construct) { + CartesianPoint3d point(0.1,0.2,0.3); + EXPECT_EQ(0.1,point.x()); + EXPECT_EQ(0.2,point.y()); + EXPECT_EQ(0.3,point.z()); + Vector3d v; v << 0.1, 0.2, 0.3; + CartesianPoint3d p2(v); + EXPECT_EQ(0.1,p2.x()); + EXPECT_EQ(0.2,p2.y()); + EXPECT_EQ(0.3,p2.z()); +} + +TEST(CartesianPointTests,assignment) { + CartesianPoint3d point; + point << 1.0, 2.0, 3.0; + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); + point.x(1.0); + point.y(2.0); + point.z(3.0); + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); + Vector3d v; v << 1.0, 2.0, 3.0; + point = v; + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); +} + +TEST(CartesianPointTests,vectorHandle) { + CartesianPoint3d point; + point << 1.0, 2.0, 3.0; + const Vector3d& v = point.positionVector(); + EXPECT_EQ(1.0,v[0]); + EXPECT_EQ(2.0,v[1]); + EXPECT_EQ(3.0,v[2]); +} + +TEST(CartesianPointTests,constAccessors) { + CartesianPoint3d point; + point << 1.0, 2.0, 3.0; + const int cx = point.x(); + const int cy = point.y(); + const int cz = point.z(); + EXPECT_EQ(1.0,cx); + EXPECT_EQ(2.0,cy); + EXPECT_EQ(3.0,cz); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/cubic_splines.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/cubic_splines.cpp new file mode 100644 index 0000000..0795d47 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/cubic_splines.cpp @@ -0,0 +1,180 @@ +/** + * @file /src/test/cubic_splines.cpp + * + * @brief Unit Test for cubic splines. + * + * @date 20/05/2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/cubic_spline.hpp" + +//#include +//#include +//#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +//using std::cout; using std::endl; +using std::string; +using ecl::Array; +//using ecl::RightAlign; +//using ecl::Format; +using ecl::CubicPolynomial; +using ecl::CubicSpline; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(CubicSplinesTests,derivativeHeuristic) { + Array x_set(3); + Array y_set(3); + x_set << 0.688792, 1.15454, 1.67894; + y_set << -0.75, -1.2, -1.30; + double ydot_0 = -0.5/x_set[0]; + double ydot_f = 1.04/3.72; + + CubicSpline cubic = CubicSpline::DerivativeHeuristic(x_set, y_set, ydot_0, ydot_f); + // cout << cubic << endl; + // + // -2.08 + 5.96x^1 + -7.85x^2 + 2.90x^3 <---- first cubic + // -0.22 + -0.72x^1 + -0.46x^2 + 0.30x^3 <---- second cubic + // + const Array& domain = cubic.domain(); + EXPECT_EQ(0.688792, domain[0]); + EXPECT_EQ(1.15454, domain[1]); + EXPECT_EQ(1.67894, domain[2]); + const CubicPolynomial &p1 = cubic.polynomials()[0]; + const CubicPolynomial &p2 = cubic.polynomials()[1]; + // allow for some roundoff errors + EXPECT_GT(-2.07,p1.coefficients()[0]); EXPECT_LT(-2.09,p1.coefficients()[0]); + EXPECT_GT(5.97,p1.coefficients()[1]); EXPECT_LT(5.95,p1.coefficients()[1]); + EXPECT_GT(-7.84,p1.coefficients()[2]); EXPECT_LT(-7.86,p1.coefficients()[2]); + EXPECT_GT(2.91,p1.coefficients()[3]); EXPECT_LT(2.89,p1.coefficients()[3]); + + EXPECT_GT(-0.21,p2.coefficients()[0]); EXPECT_LT(-0.23,p2.coefficients()[0]); + EXPECT_GT(-0.71,p2.coefficients()[1]); EXPECT_LT(-0.73,p2.coefficients()[1]); + EXPECT_GT(-0.45,p2.coefficients()[2]); EXPECT_LT(-0.47,p2.coefficients()[2]); + EXPECT_GT(0.31,p2.coefficients()[3]); EXPECT_LT(0.29,p2.coefficients()[3]); + +// /********************* +// ** Output +// **********************/ +// Format string_format; string_format.width(6); string_format.align(RightAlign); +// Format format; format.width(6); format.precision(2); format.align(RightAlign); +// cout << string_format("x "); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''") << endl; +// int n = 50; +// for ( int i = 0; i <= n; ++i ) { +// double x = x_set[0] + i*(x_set.back()-x_set.front())/n; +// cout << format(x); +// cout << format(cubic(x)); +// cout << format(cubic.derivative(x)); +// cout << format(cubic.dderivative(x)) << endl; +// } +} + + +TEST(CubicSplinesTests,continuousHeuristic) { + Array x_set(3); + Array y_set(3); + x_set << 0.688792, 1.15454, 1.67894; + y_set << -0.75, -1.2, -1.30; + double ydot_0 = -0.5/x_set[0]; + double ydot_f = 1.04/3.72; + CubicSpline cubic = CubicSpline::ContinuousDerivatives(x_set, y_set, ydot_0, ydot_f); + const CubicPolynomial &p1 = cubic.polynomials()[0]; + const CubicPolynomial &p2 = cubic.polynomials()[1]; + // allow for some roundoff errors + EXPECT_GT(-1.57,p1.coefficients()[0]); EXPECT_LT(-1.59,p1.coefficients()[0]); + EXPECT_GT(4.10,p1.coefficients()[1]); EXPECT_LT(4.08,p1.coefficients()[1]); + EXPECT_GT(-5.53,p1.coefficients()[2]); EXPECT_LT(-5.55,p1.coefficients()[2]); + EXPECT_GT(2.00,p1.coefficients()[3]); EXPECT_LT(1.98,p1.coefficients()[3]); + + EXPECT_GT(2.13,p2.coefficients()[0]); EXPECT_LT(2.11,p2.coefficients()[0]); + EXPECT_GT(-5.51,p2.coefficients()[1]); EXPECT_LT(-5.53,p2.coefficients()[1]); + EXPECT_GT(2.79,p2.coefficients()[2]); EXPECT_LT(2.77,p2.coefficients()[2]); + EXPECT_GT(-0.41,p2.coefficients()[3]); EXPECT_LT(-0.43,p2.coefficients()[3]); +// /********************* +// ** Output +// **********************/ +// std::cout << cubic << std::endl; +// Format string_format; string_format.width(6); string_format.align(RightAlign); +// Format format; format.width(6); format.precision(2); format.align(RightAlign); +// cout << string_format("x "); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''") << endl; +// int n = 50; +// for ( int i = 0; i <= n; ++i ) { +// double x = x_set[0] + i*(x_set.back()-x_set.front())/n; +// cout << format(x); +// cout << format(cubic_c2(x)); +// cout << format(cubic_c2.derivative(x)); +// cout << format(cubic_c2.dderivative(x)) << endl; +// } +} + +TEST(CubicSplinesTests,naturalSpline) { + Array x_set(3); + Array y_set(3); + x_set << 0.688792, 1.15454, 1.67894; + y_set << -0.75, -1.2, -1.30; + + CubicSpline cubic = CubicSpline::Natural(x_set, y_set); + const CubicPolynomial &p1 = cubic.polynomials()[0]; + const CubicPolynomial &p2 = cubic.polynomials()[1]; + // allow for some roundoff errors + EXPECT_GT(-0.22,p1.coefficients()[0]); EXPECT_LT(-0.24,p1.coefficients()[0]); + EXPECT_GT(0.06,p1.coefficients()[1]); EXPECT_LT(0.04,p1.coefficients()[1]); + EXPECT_GT(-1.73,p1.coefficients()[2]); EXPECT_LT(-1.75,p1.coefficients()[2]); + EXPECT_GT(0.85,p1.coefficients()[3]); EXPECT_LT(0.83,p1.coefficients()[3]); + + EXPECT_GT(2.22,p2.coefficients()[0]); EXPECT_LT(2.20,p2.coefficients()[0]); + EXPECT_GT(-6.29,p2.coefficients()[1]); EXPECT_LT(-6.31,p2.coefficients()[1]); + EXPECT_GT(3.77,p2.coefficients()[2]); EXPECT_LT(3.75,p2.coefficients()[2]); + EXPECT_GT(-0.74,p2.coefficients()[3]); EXPECT_LT(-0.76,p2.coefficients()[3]); + +// /********************* +// ** Output +// **********************/ +// Format string_format; string_format.width(6); string_format.align(RightAlign); +// Format format; format.width(6); format.precision(2); format.align(RightAlign); +// cout << string_format("x "); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''") << endl; +// int n = 50; +// for ( int i = 0; i <= n; ++i ) { +// double x = x_set[0] + i*(x_set.back()-x_set.front())/n; +// cout << format(x); +// cout << format(cubic(x)); +// cout << format(cubic.derivative(x)); +// cout << format(cubic.dderivative(x)) << endl; +// } +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/homogeneous_points.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/homogeneous_points.cpp new file mode 100644 index 0000000..5494e84 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/homogeneous_points.cpp @@ -0,0 +1,96 @@ +/** + * @file /src/test/homogeneous_points.cpp + * + * @brief Unit Test for the homogeneous point classes. + * + * @date March 2012 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/geometry/homogeneous_point.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::linear_algebra::Vector3d; +using ecl::linear_algebra::Vector4d; +using ecl::linear_algebra::Vector4f; +using ecl::HomogeneousPoint; +using ecl::HomogeneousPointf; +using ecl::HomogeneousPointd; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(HomogeneousPointTests,construct) { + HomogeneousPointd point(0.1,0.2,0.3); + EXPECT_EQ(0.1,point.x()); + EXPECT_EQ(0.2,point.y()); + EXPECT_EQ(0.3,point.z()); + Vector4d v; v << 0.1, 0.2, 0.3, 1.0; + HomogeneousPointd p2(v); + EXPECT_EQ(0.1,p2.x()); + EXPECT_EQ(0.2,p2.y()); + EXPECT_EQ(0.3,p2.z()); + Vector3d v3; v3 << 1.0, 2.0, 3.0; + HomogeneousPointd p3(v3); + EXPECT_EQ(1.0,p3.x()); + EXPECT_EQ(2.0,p3.y()); + EXPECT_EQ(3.0,p3.z()); +} + +TEST(HomogeneousPointTests,assignment) { + HomogeneousPointf point; + point << 1.0, 2.0, 3.0, 1.0; + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); + point.x(1.0); + point.y(2.0); + point.z(3.0); + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); + Vector4f v; v << 1.0, 2.0, 3.0, 1.0; + point = v; + EXPECT_EQ(1.0,point.x()); + EXPECT_EQ(2.0,point.y()); + EXPECT_EQ(3.0,point.z()); +} + +TEST(HomogeneousPointTests,vectorHandle) { + HomogeneousPointd point; + point << 1.0, 2.0, 3.0, 1.0; + const Vector4d& v = point.positionVector(); + EXPECT_EQ(1.0,v[0]); + EXPECT_EQ(2.0,v[1]); + EXPECT_EQ(3.0,v[2]); +} + +TEST(HomogeneousPointTests,constAccessors) { + HomogeneousPointd point; + point << 1.0, 2.0, 3.0, 1.0; + const int cx = point.x(); + const int cy = point.y(); + const int cz = point.z(); + EXPECT_EQ(1.0,cx); + EXPECT_EQ(2.0,cy); + EXPECT_EQ(3.0,cz); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose2d.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose2d.cpp new file mode 100644 index 0000000..7f35024 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose2d.cpp @@ -0,0 +1,267 @@ +/** + * @file /src/test/pose2d.cpp + * + * @ingroup UnitTests + * + * Use this to test the Pose2D class + * + * @date August 2010 + **/ +/***************************************************************************** +** Defines +*****************************************************************************/ + +#define ECL_USE_EIGEN3 + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/angle.hpp" +#include "../../include/ecl/geometry/legacy_pose2d.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Angle; +using ecl::LegacyPose2D; +using ecl::RotationAngleStorage; +using ecl::linear_algebra::Matrix2d; +using ecl::linear_algebra::Vector2d; +using ecl::linear_algebra::Vector3d; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(LegacyPose2DTests,RotationMatrixConstructors) { + LegacyPose2D pose1; + EXPECT_EQ(0.0,pose1.x()); + EXPECT_EQ(0.0,pose1.y()); + EXPECT_GT(1.01,pose1.rotation()(0,0)); + EXPECT_LT(0.99,pose1.rotation()(0,0)); + EXPECT_GT(0.01,pose1.rotation()(0,1)); + EXPECT_LT(-0.01,pose1.rotation()(0,1)); + EXPECT_GT(0.01,pose1.rotation()(1,0)); + EXPECT_LT(-0.01,pose1.rotation()(1,0)); + EXPECT_GT(1.01,pose1.rotation()(1,1)); + EXPECT_LT(0.99,pose1.rotation()(1,1)); + LegacyPose2D pose2(1.0, 2.0, 3.14); + EXPECT_EQ(1.0,pose2.x()); + EXPECT_EQ(2.0,pose2.y()); + EXPECT_EQ(3.14,pose2.heading()); + Vector2d trans; trans << 1.0, 2.0; + Matrix2d rot = Angle(3.14).rotationMatrix(); + LegacyPose2D pose3(rot,trans); + EXPECT_EQ(1.0,pose3.x()); + EXPECT_EQ(2.0,pose3.y()); + EXPECT_GT(3.15, pose3.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose3.heading()); + LegacyPose2D pose4(3.14,trans); + EXPECT_EQ(1.0,pose4.x()); + EXPECT_EQ(2.0,pose4.y()); + EXPECT_GT(3.15, pose4.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose4.heading()); + LegacyPose2D pose5(pose4); + EXPECT_EQ(1.0,pose5.x()); + EXPECT_EQ(2.0,pose5.y()); + EXPECT_GT(3.15, pose5.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose5.heading()); + LegacyPose2D pose_other(3.14,trans); + LegacyPose2D pose6(pose_other); + EXPECT_EQ(1.0,pose6.x()); + EXPECT_EQ(2.0,pose6.y()); + EXPECT_GT(3.15, pose6.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose6.heading()); +} + +TEST(LegacyPose2DTests,RotationAngleConstructors) { + LegacyPose2D pose1; + EXPECT_EQ(0.0,pose1.x()); + EXPECT_EQ(0.0,pose1.y()); + EXPECT_GT(0.01,pose1.rotation()); + EXPECT_LT(-0.01,pose1.rotation()); + LegacyPose2D pose2(1.0, 2.0, 3.14); + EXPECT_EQ(1.0,pose2.x()); + EXPECT_EQ(2.0,pose2.y()); + EXPECT_EQ(3.14,pose2.heading()); + Vector2d trans; trans << 1.0, 2.0; + Matrix2d rot = Angle(3.14).rotationMatrix(); + LegacyPose2D pose3(rot,trans); + EXPECT_EQ(1.0,pose3.x()); + EXPECT_EQ(2.0,pose3.y()); + EXPECT_GT(3.15, pose3.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose3.heading()); + LegacyPose2D pose4(3.14,trans); + EXPECT_EQ(1.0,pose4.x()); + EXPECT_EQ(2.0,pose4.y()); + EXPECT_GT(3.15, pose4.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose4.heading()); + LegacyPose2D pose5(pose4); + EXPECT_EQ(1.0,pose5.x()); + EXPECT_EQ(2.0,pose5.y()); + EXPECT_GT(3.15, pose5.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose5.heading()); + LegacyPose2D pose_other(1.0, 2.0, 3.14); + LegacyPose2D pose6(pose_other); + EXPECT_EQ(1.0,pose6.x()); + EXPECT_EQ(2.0,pose6.y()); + EXPECT_GT(3.15, pose6.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose6.heading()); +} + +TEST(LegacyPose2DTests,assignment) { + LegacyPose2D pose_r1(2.0, 1.0, 1.14); + LegacyPose2D pose_a1(1.0, 2.0, 3.14); + LegacyPose2D pose_r2; + LegacyPose2D pose_a2; + pose_r2 = pose_r1; + EXPECT_EQ(2.0,pose_r2.x()); + EXPECT_EQ(1.0,pose_r2.y()); + EXPECT_GT(1.15, pose_r2.heading());// Allow some roundoff error here + EXPECT_LT(1.13, pose_r2.heading()); + pose_r2 = pose_a1; + EXPECT_EQ(1.0,pose_r2.x()); + EXPECT_EQ(2.0,pose_r2.y()); + EXPECT_GT(3.15, pose_r2.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose_r2.heading()); + pose_a2 = pose_r1; + EXPECT_EQ(2.0,pose_a2.x()); + EXPECT_EQ(1.0,pose_a2.y()); + EXPECT_GT(1.15, pose_a2.heading());// Allow some roundoff error here + EXPECT_LT(1.13, pose_a2.heading()); + pose_a2 = pose_a1; + EXPECT_EQ(1.0,pose_a2.x()); + EXPECT_EQ(2.0,pose_a2.y()); + EXPECT_GT(3.15, pose_a2.heading());// Allow some roundoff error here + EXPECT_LT(3.13, pose_a2.heading()); +} + +TEST(LegacyPose2DTests,eigenStyle) { + Vector2d trans; trans << 1.0, 2.0; + Matrix2d rot = Angle(3.14).rotationMatrix(); + LegacyPose2D rpose; + rpose.rotation(rot); + rpose.translation(trans); + EXPECT_EQ(1.0,rpose.x()); + EXPECT_EQ(2.0,rpose.y()); + EXPECT_GT(3.15, rpose.heading());// Allow some roundoff error here + EXPECT_LT(3.13, rpose.heading()); + rot = rpose.rotation(); + trans = rpose.translation(); + EXPECT_EQ(1.0,trans[0]); + EXPECT_EQ(2.0,trans[1]); + EXPECT_GT(3.15, Angle(rot));// Allow some roundoff error here + EXPECT_LT(3.13, Angle(rot)); + LegacyPose2D apose; + apose.rotation(3.14); + apose.translation(trans); + EXPECT_EQ(1.0,apose.x()); + EXPECT_EQ(2.0,apose.y()); + EXPECT_GT(3.15, apose.heading());// Allow some roundoff error here + EXPECT_LT(3.13, apose.heading()); + double angle = apose.rotation(); + trans = apose.translation(); + EXPECT_EQ(1.0,trans[0]); + EXPECT_EQ(2.0,trans[1]); + EXPECT_GT(3.15, angle);// Allow some roundoff error here + EXPECT_LT(3.13, angle); +} +TEST(LegacyPose2DTests,convenienceStyle) { + Vector2d trans; trans << 1.0, 2.0; + Matrix2d rot; + LegacyPose2D rpose; + rpose.x(1.0); rpose.y(2.0); rpose.heading(3.14); + EXPECT_EQ(1.0,rpose.x()); + EXPECT_EQ(2.0,rpose.y()); + EXPECT_GT(3.15, rpose.heading());// Allow some roundoff error here + EXPECT_LT(3.13, rpose.heading()); + rpose.heading(0.0); + rot = rpose.rotationMatrix(); + EXPECT_GT(1.01,rot(0,0)); + EXPECT_LT(0.99,rot(0,0)); + EXPECT_GT(0.01,rot(0,1)); + EXPECT_LT(-0.01,rot(0,1)); + EXPECT_GT(0.01,rot(1,0)); + EXPECT_LT(-0.01,rot(1,0)); + EXPECT_GT(1.01,rot(1,1)); + EXPECT_LT(0.99,rot(1,1)); + LegacyPose2D apose; + apose.x(1.0); apose.y(2.0); apose.heading(3.14); + EXPECT_EQ(1.0,apose.x()); + EXPECT_EQ(2.0,apose.y()); + EXPECT_GT(3.15, apose.heading());// Allow some roundoff error here + EXPECT_LT(3.13, apose.heading()); + apose.heading(0.0); + rot = apose.rotationMatrix(); + EXPECT_GT(1.01,rot(0,0)); + EXPECT_LT(0.99,rot(0,0)); + EXPECT_GT(0.01,rot(0,1)); + EXPECT_LT(-0.01,rot(0,1)); + EXPECT_GT(0.01,rot(1,0)); + EXPECT_LT(-0.01,rot(1,0)); + EXPECT_GT(1.01,rot(1,1)); + EXPECT_LT(0.99,rot(1,1)); +} +TEST(LegacyPose2DTests,inverse) { + LegacyPose2D pose(1.0, 2.0, ecl::pi); + LegacyPose2D inverse = pose.inverse(); + EXPECT_GT(1.01,inverse.x()); // Allow some roundoff error here + EXPECT_LT(0.99,inverse.x()); + EXPECT_GT(2.01,inverse.y()); // Allow some roundoff error here + EXPECT_LT(1.99,inverse.y()); + EXPECT_GT(-ecl::pi+0.01,inverse.heading()); // Allow some roundoff error here + EXPECT_LT(-ecl::pi-0.01,inverse.heading()); + LegacyPose2D apose(1.0, 2.0, ecl::pi); + LegacyPose2D ainverse = pose.inverse(); + EXPECT_GT(1.01,ainverse.x()); // Allow some roundoff error here + EXPECT_LT(0.99,ainverse.x()); + EXPECT_GT(2.01,ainverse.y()); // Allow some roundoff error here + EXPECT_LT(1.99,ainverse.y()); + EXPECT_GT(-ecl::pi+0.01,ainverse.heading()); // Allow some roundoff error here + EXPECT_LT(-ecl::pi-0.01,ainverse.heading()); +} + +TEST(LegacyPose2DTests,operators) { + LegacyPose2D a(1.0, 2.0, 0.0), b(1.0, 3.0, ecl::pi); + LegacyPose2D diff = a.inverse()*b; // diff = b - a; + EXPECT_EQ(0.0,diff.x()); + EXPECT_EQ(1.0,diff.y()); + EXPECT_EQ(ecl::pi,diff.heading()); + LegacyPose2D a2(1.0, 2.0, 0.0), b2(1.0, 3.0, ecl::pi); + LegacyPose2D diff2 = a2.inverse()*b2; // diff = b - a; + EXPECT_EQ(0.0,diff2.x()); + EXPECT_EQ(1.0,diff2.y()); + EXPECT_EQ(ecl::pi,diff2.heading()); +} +TEST(LegacyPose2DTests,relative) { + LegacyPose2D a(1.0, 1.0, 1.57), b(1.0, 2.0, 3.14); + LegacyPose2D brela = b.relative(a); + EXPECT_GT(1.01,brela.x()); + EXPECT_LT(0.99,brela.x()); + EXPECT_GT(0.01,brela.y()); + EXPECT_LT(-0.01,brela.y()); + EXPECT_GT(1.58,brela.heading()); + EXPECT_LT(1.56,brela.heading()); + LegacyPose2D a_(1.0, 1.0, 1.57), b_(1.0, 2.0, 3.14); + LegacyPose2D brela_ = b.relative(a); + EXPECT_GT(1.01,brela_.x()); + EXPECT_LT(0.99,brela_.x()); + EXPECT_GT(0.01,brela_.y()); + EXPECT_LT(-0.01,brela_.y()); + EXPECT_GT(1.58,brela_.heading()); + EXPECT_LT(1.56,brela_.heading()); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose3d.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose3d.cpp new file mode 100644 index 0000000..e258725 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/legacy_pose3d.cpp @@ -0,0 +1,128 @@ +/** + * @file /src/test/pose3d.cpp + * + * @ingroup UnitTests + * + * Use this to test the Pose3D class + * + * @date September 2010 + **/ +/***************************************************************************** +** Preprocessor +*****************************************************************************/ + +#define ECL_USE_EIGEN3 1 + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/legacy_pose2d.hpp" +#include "../../include/ecl/geometry/legacy_pose3d.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::LegacyPose2D; +using ecl::LegacyPose3D; +using ecl::linear_algebra::AngleAxis; +using ecl::linear_algebra::Matrix3d; +using ecl::linear_algebra::Vector3d; +using ecl::linear_algebra::Quaternion; +using ecl::linear_algebra::Translation3d; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(LegacyPose3DTests,constructors) { + bool result; + Vector3d v; v << 1.0,2.0,3.0; + Matrix3d zero_rotation = Matrix3d::Identity(); + Vector3d zero_translation; zero_translation << 0.0,0.0,0.0; + LegacyPose2D pose_2d(0.0,1.0,ecl::pi); + LegacyPose3D pose1(zero_rotation,v); + EXPECT_TRUE(pose1.rotation().isApprox(zero_rotation,0.1)); + EXPECT_TRUE(pose1.translation().isApprox(v,0.1)); + LegacyPose3D pose2(pose_2d); + result = pose2.rotation().block<2,2>(0,0).isApprox(pose_2d.rotationMatrix(),0.1); + EXPECT_TRUE(result); + result = pose2.translation().segment<2>(0).isApprox(pose_2d.translation(),0.1); + EXPECT_TRUE(result); + LegacyPose3D pose3(Quaternion(pose2.rotation()),v); + EXPECT_TRUE(pose3.rotation().isApprox(pose2.rotation(),0.1)); + EXPECT_TRUE(pose3.translation().isApprox(v,0.1)); + LegacyPose3D pose4(pose3); + EXPECT_TRUE(pose4.rotation().isApprox(pose3.rotation(),0.1)); + EXPECT_TRUE(pose4.translation().isApprox(pose3.translation(),0.1)); +} + + +TEST(LegacyPose3DTests,assignment) { + Vector3d v; v << 0.0,1.0,0.0; + Matrix3d rot; rot << -1.0, 0.0, 0.0, + 0.0, -1.0, 0.0, + 0.0, 0.0, 1.0;; + LegacyPose2D pose_2d(0.0,1.0,ecl::pi); + LegacyPose3D pose1, pose2; + pose1 = pose_2d; + EXPECT_TRUE(pose1.rotation().isApprox(rot,0.1)); + EXPECT_TRUE(pose1.translation().isApprox(v,0.1)); + pose2 = pose1; + EXPECT_TRUE(pose2.rotation().isApprox(rot,0.1)); + EXPECT_TRUE(pose2.translation().isApprox(v,0.1)); +} + +TEST(LegacyPose3DTests,eigenStyle) { + Vector3d v; v << 0.0,1.0,0.0; + Matrix3d rot; rot << -1.0, 0.0, 0.0, + 0.0, -1.0, 0.0, + 0.0, 0.0, 1.0;; + LegacyPose3D pose1; + pose1.rotation(rot); + pose1.translation(v); + EXPECT_TRUE(pose1.rotation().isApprox(rot,0.1)); + EXPECT_TRUE(pose1.translation().isApprox(v,0.1)); +} +TEST(LegacyPose3DTests,inverse) { + Vector3d z_axis; z_axis << 0.0, 0.0, 1.0; + Vector3d zero = Vector3d::Zero(); + Matrix3d rot = AngleAxis(ecl::pi/2.0,z_axis).toRotationMatrix(); + Vector3d trans; trans << 1.0, 2.0, 3.0; + LegacyPose3D pose(rot, trans); + LegacyPose3D inverse = pose.inverse(); + LegacyPose3D repose = pose*inverse; + EXPECT_TRUE(Matrix3d::Identity().isApprox(repose.rotation(),0.1)); + for ( unsigned int i = 0; i < 3; ++i ) { + EXPECT_LT(zero[i],repose.translation()[i]+0.01); + EXPECT_GT(zero[i]+0.01,repose.translation()[i]); + } +} + +TEST(LegacyPose3DTests,operators) { + Vector3d z_axis; z_axis << 0.0, 0.0, 1.0; + Matrix3d rot = AngleAxis(ecl::pi/2.0,z_axis).toRotationMatrix(); + Matrix3d rot_pi = AngleAxis(ecl::pi,z_axis).toRotationMatrix(); + Vector3d trans; trans << 1.0, 2.0, 3.0; + Vector3d expected_final_trans; expected_final_trans << -1.0, 3.0, 6.0; + LegacyPose3D pose(rot, trans); + LegacyPose3D final_pose = pose*pose; + EXPECT_TRUE(rot_pi.isApprox(final_pose.rotation())); + EXPECT_TRUE(expected_final_trans.isApprox(final_pose.translation())); + pose *= pose; + EXPECT_TRUE(rot_pi.isApprox(pose.rotation())); + EXPECT_TRUE(expected_final_trans.isApprox(pose.translation())); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/linear_segment.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/linear_segment.cpp new file mode 100644 index 0000000..34358a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/linear_segment.cpp @@ -0,0 +1,73 @@ +/** + * @file /src/test/linear_segment.cpp + * + * @ingroup UnitTests + * + * Use this to test the linear segment classes. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/geometry/linear_segment.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(LinearSegment,construction) { + ecl::LinearSegment horizontal_segment(0.0,1.0,4.0,1.0); + EXPECT_EQ(0.0, horizontal_segment.A()); + EXPECT_EQ(1.0, horizontal_segment.B()); + EXPECT_EQ(-1.0, horizontal_segment.C()); + ecl::LinearSegment vertical_segment(2.0,1.0,2.0,4.0); + EXPECT_EQ(1.0, vertical_segment.A()); + EXPECT_EQ(0.0, vertical_segment.B()); + EXPECT_EQ(2.0, vertical_segment.C()); + ecl::LinearSegment segment(0.0,1.0,1.0,2.0); + EXPECT_EQ(-1.0, segment.A()); + EXPECT_EQ(1.0, segment.B()); + EXPECT_EQ(-1.0, segment.C()); +// EXPECT_GT(0.786,f); // Allow some roundoff error here +// EXPECT_LT(0.785,f); +} + +TEST(LinearSegment,distance) { + ecl::LinearSegment horizontal_segment(0.0,1.0,4.0,1.0); + EXPECT_EQ(1.0, horizontal_segment.squaredDistanceFromPoint(0.0, 2.0)); + EXPECT_EQ(1.0, horizontal_segment.squaredDistanceFromPoint(-1.0, 1.0)); + EXPECT_EQ(0.0, horizontal_segment.squaredDistanceFromPoint(1.0, 1.0)); + EXPECT_EQ(1.0, horizontal_segment.squaredDistanceFromPoint(4.0, 0.0)); + ecl::LinearSegment vertical_segment(2.0,1.0,2.0,3.0); + EXPECT_EQ(1.0, vertical_segment.squaredDistanceFromPoint(2.0, 0.0)); + EXPECT_EQ(1.0, vertical_segment.squaredDistanceFromPoint(1.0, 1.0)); + EXPECT_EQ(1.0, vertical_segment.squaredDistanceFromPoint(3.0, 1.0)); + EXPECT_EQ(1.0, vertical_segment.squaredDistanceFromPoint(1.0, 2.0)); + ecl::LinearSegment segment(0.0,1.0,1.0,2.0); + EXPECT_EQ(1.0, segment.squaredDistanceFromPoint(1.0, 3.0)); + EXPECT_EQ(0.0, segment.squaredDistanceFromPoint(0.5, 1.5)); + +// EXPECT_GT(0.786,f); // Allow some roundoff error here +// EXPECT_LT(0.785,f); +} + +// operator tests + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/odometry_helper.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/odometry_helper.cpp new file mode 100644 index 0000000..03a2ce8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/odometry_helper.cpp @@ -0,0 +1,182 @@ +/** + * @file /src/test/odometry_helper.cpp + * + * @ingroup UnitTests + * + * Use this to test the odometry helper functions. + * + * @date November 2016 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/geometry/odometry_helper.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::odometry; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + + TEST(OdometryTests,distances) { + Trajectory2D trajectory(3, 5); + + /** ______ + * \_ | + * \ | + * | + * ______| + */ + trajectory << -2.0, 2.0, 2.0, -2.0, 0.0, + -2.0, -2.0, 2.0, 2.0, 0.0, + 0.3, -2.3, 0.0, 4.0, -4.0; + + Pose2D pose; + double distance_pose = 0.0; + double distance_position = 0.0; + + pose = Pose2D(0.0, -3.0, 4.0); + distance_pose = distance(pose, trajectory); + + EXPECT_EQ(1.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(3.0, 1.0, 0.1); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(1.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(-3.0, 1.0, -0.1); + distance_pose = distance(pose, trajectory); + // diagnoal -> sqrt(2) + EXPECT_GT(1.4143, distance_pose); + EXPECT_LT(1.4142, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(1.0, 3.0, -3.2); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(1.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(1.0, -3.0, 4.1); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(1.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(-2.0, -4.0, 0.1); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(2.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(-2.0, -2.0, 0.1); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(0.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + + pose = Pose2D(1.0, 0.0, -8.0); + distance_pose = distance(pose, trajectory); + EXPECT_EQ(1.0, distance_pose); + distance_position = distance(getPosition(pose), trajectory); + EXPECT_EQ(distance_pose, distance_position); + } + + TEST(OdometryTests,trajectories) { + Trajectory2DPtr trajectory; + EXPECT_EQ(true, empty(trajectory)); + + Odom2DTrajectoryPtr odom_traj; + EXPECT_EQ(true, empty(odom_traj)); + + trajectory = std::make_shared(); + EXPECT_EQ(true, empty(trajectory)); + EXPECT_EQ(0, size(trajectory)); + EXPECT_EQ(0, size(*trajectory)); + + odom_traj = std::make_shared(); + EXPECT_EQ(true, empty(odom_traj)); + EXPECT_EQ(0, size(odom_traj)); + EXPECT_EQ(0, size(*odom_traj)); + + trajectory = std::make_shared(3, 1); + *trajectory << 0.0, 0.0, 0.0; + EXPECT_EQ(false, empty(trajectory)); + EXPECT_EQ(1, size(trajectory)); + EXPECT_EQ(1, size(*trajectory)); + + odom_traj = std::make_shared(6, 1); + *odom_traj << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0; + EXPECT_EQ(false, empty(odom_traj)); + EXPECT_EQ(1, size(odom_traj)); + EXPECT_EQ(1, size(*odom_traj)); + + resize(*trajectory, 4); + EXPECT_EQ(false, empty(trajectory)); + EXPECT_EQ(4, size(trajectory)); + EXPECT_EQ(4, size(*trajectory)); + + resize(*odom_traj, 7); + EXPECT_EQ(false, empty(odom_traj)); + EXPECT_EQ(7, size(odom_traj)); + EXPECT_EQ(7, size(*odom_traj)); + + resize(*trajectory, 0); + EXPECT_EQ(true, empty(trajectory)); + EXPECT_EQ(0, size(trajectory)); + EXPECT_EQ(0, size(*trajectory)); + + resize(*odom_traj, 0); + EXPECT_EQ(true, empty(odom_traj)); + EXPECT_EQ(0, size(odom_traj)); + EXPECT_EQ(0, size(*odom_traj)); + + resize(*odom_traj, 3); + addAtEnd(*trajectory, getPoses(*odom_traj)); + EXPECT_EQ(false, empty(trajectory)); + EXPECT_EQ(3, size(trajectory)); + EXPECT_EQ(3, size(*trajectory)); + + EXPECT_EQ(getAt(*trajectory, 0), getPose(getAt(*odom_traj, 0))); + EXPECT_EQ(getAt(*trajectory, 2), getAt(getPoses(*odom_traj), 2)); + + EXPECT_EQ(getAt(*trajectory, 0), getFront(*trajectory)); + EXPECT_EQ(getAt(*odom_traj, 0), getFront(*odom_traj)); + + EXPECT_EQ(getAt(*trajectory, size(trajectory) - 1), getBack(*trajectory)); + EXPECT_EQ(getAt(*odom_traj, 2), getBack(*odom_traj)); + + setAt(*trajectory, 2, getFront(*trajectory)); + EXPECT_EQ(getAt(*trajectory, 2), getFront(*trajectory)); + + setAt(*odom_traj, 1, getFront(*odom_traj)); + EXPECT_EQ(getAt(*odom_traj, 1), getFront(*odom_traj)); + } +#endif + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/polynomials.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/polynomials.cpp new file mode 100644 index 0000000..485f953 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/polynomials.cpp @@ -0,0 +1,238 @@ +/** + * @file /src/test/polynomials.cpp + * + * @brief Unit Test for polynomial functions. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/geometry/cartesian_point.hpp" +#include "../../include/ecl/geometry/pascals_triangle.hpp" +#include "../../include/ecl/geometry/polynomial.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::CartesianPoint2d; +using ecl::RightAlign; +using ecl::Format; +using ecl::Division; +using ecl::Intersection; +using ecl::LinearFunction; +using ecl::QuadraticPolynomial; +using ecl::CubicPolynomial; +using ecl::PascalsTriangle; +using ecl::Polynomial; +using ecl::QuinticPolynomial; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(PolynomialTests,pascalsTriangle) { + +// 1 1 1 1 +// 1 2 3 +// 1 3 +// 1 + PascalsTriangle<3> pascals_triangle_three; + PascalsTriangle<3>::const_iterator iter3 = pascals_triangle_three.begin(); + EXPECT_EQ(2,*(iter3+5)); + +// 1 1 1 1 1 1 +// 1 2 3 4 5 +// 1 3 6 10 +// 1 4 10 +// 1 5 +// 1 + PascalsTriangle<5> pascals_triangle; + PascalsTriangle<5>::const_iterator iter5 = pascals_triangle.begin(); + EXPECT_EQ(3,*(iter5+8)); + +// 1 1 1 1 1 +// 1 2 3 4 +// 1 3 6 +// 1 4 +// 1 + PascalsTriangle<4> pascals_triangle_four; + PascalsTriangle<4>::const_iterator iter4 = pascals_triangle_four.begin(); + EXPECT_EQ(4,*(iter4+8)); +} + +TEST(PolynomialTests,quadratic) { + Polynomial<2> p; + p.coefficients() << 0, 1, 1; + EXPECT_EQ(0,p.coefficients()[0]); + EXPECT_EQ(1,p.coefficients()[1]); + EXPECT_EQ(1,p.coefficients()[2]); +// std::cout << "p(5.3) = " << p(5.3) << std::endl; + // Allow some roundoff error here + EXPECT_GT(33.40,p(5.3)); EXPECT_LT(33.38,p(5.3)); + p.shift_horizontal(2); +// std::cout << "p(x-2)(5.3) = " << p(5.3) << std::endl; + EXPECT_GT(14.20,p(5.3)); EXPECT_LT(14.18,p(5.3)); +} + +TEST(PolynomialTests,cubic) { + CubicPolynomial p; + p.coefficients() << 3, 1, 1, 1; +// double maximum = ecl::Maximum()(0.0, 0.2, p); + double maximum = ecl::CubicPolynomial::Maximum(0.0, 0.2, p); + //std::cout << p << std::endl; + //std::cout << "Maximum [0.0, 0.2]: " << maximum << std::endl; + EXPECT_DOUBLE_EQ(maximum, 3.248); +} + +TEST(PolynomialTests,linear_function) { + LinearFunction f, g; + f = LinearFunction::PointSlopeForm(1.0,3.0,2.0); + g = LinearFunction::PointSlopeForm(0.0,4.0,-1.0); + CartesianPoint2d point = LinearFunction::Intersection(f,g); + EXPECT_DOUBLE_EQ(point.x(),1.0); + EXPECT_DOUBLE_EQ(point.y(),3.0); + //std::cout << "Intersection: " << point << std::endl; + bool caught = false; + Intersection intersection; + try { + point = intersection(f,f); + } catch ( ecl::StandardException &e ) { + // collinear + caught = true; + } + EXPECT_EQ(caught, true); + EXPECT_EQ(intersection.fail(),true); +} + +TEST(PolynomialTests,roots) { + ecl::Array roots; + LinearFunction f = LinearFunction::PointSlopeForm(1.0,3.0,2.0); + roots = LinearFunction::Roots(f); + EXPECT_EQ(1U,roots.size()); + if ( roots.size() > 0 ) { + EXPECT_DOUBLE_EQ(-0.5,roots[0]); + } + QuadraticPolynomial q; + q.coefficients() << 1.0, 2.0, 1.0; // x^2 + 2x + 1 (single root) + roots = QuadraticPolynomial::Roots(q); + EXPECT_EQ(1U,roots.size()); + if ( roots.size() > 0 ) { + EXPECT_DOUBLE_EQ(-1.0,roots[0]); + } + q.coefficients() << 2.0, 2.0, 1.0; // x^2 + 2x + 2 (no roots) + roots = QuadraticPolynomial::Roots(q); + EXPECT_EQ(0U,roots.size()); + q.coefficients() << -2.0, 1.0, 1.0; // x^2 + x -2 (two roots) + roots = QuadraticPolynomial::Roots(q); + EXPECT_EQ(2U,roots.size()); + EXPECT_DOUBLE_EQ(1,roots[0]); + EXPECT_DOUBLE_EQ(-2,roots[1]); + CubicPolynomial c; + c.coefficients() << -6.0, 1.0, 4.0, 1.0; // x^3 + 4x^2 + x - 6 = (x-1)(x+2)(x+3) three roots + roots = CubicPolynomial::Roots(c); + EXPECT_EQ(3U,roots.size()); + if ( roots.size() == 3 ) { + EXPECT_DOUBLE_EQ(1,roots[0]); + EXPECT_DOUBLE_EQ(-2,roots[1]); + EXPECT_DOUBLE_EQ(-3,roots[2]); + } + c.coefficients() << 0, 0, 0, 1.0; // x^3 one triple root + roots = CubicPolynomial::Roots(c); + EXPECT_EQ(1U,roots.size()); + if ( roots.size() == 1 ) { + EXPECT_DOUBLE_EQ(0,roots[0]); + } + c.coefficients() << -1.0, 1.0, -1.0, 1.0; // (x-1)^3 shifted by one (one real, two complex) + roots = CubicPolynomial::Roots(c); + EXPECT_EQ(1U,roots.size()); + if ( roots.size() == 1 ) { + EXPECT_DOUBLE_EQ(1,roots[0]); + } +} +TEST(PolynomialTests,division) { + CubicPolynomial c; + c.coefficients() << -6.0, 1.0, 4.0, 1.0; // x^3 + 4x^2 + x - 6 = (x-1)(x+2)(x+3) three roots + ecl::FunctionMath math; + double remainder; + QuadraticPolynomial q = CubicPolynomial::Division(c, 1, remainder); // x^2 + 5x + 6 + EXPECT_DOUBLE_EQ(6.0, q.coefficients()[0]); + EXPECT_DOUBLE_EQ(5.0, q.coefficients()[1]); + EXPECT_DOUBLE_EQ(1.0, q.coefficients()[2]); + EXPECT_DOUBLE_EQ(0.0, remainder); + LinearFunction f = QuadraticPolynomial::Division(q, -2, remainder); + EXPECT_DOUBLE_EQ(3.0, f.coefficients()[0]); // x + 3 + EXPECT_DOUBLE_EQ(1.0, f.coefficients()[1]); + EXPECT_DOUBLE_EQ(0.0, remainder); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + // Haven't got around to gtesting these yet. + + Format string_format; string_format.width(8); string_format.align(RightAlign); + Format format; format.width(8); format.precision(2); format.align(RightAlign); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Polynomial Blueprints" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + LinearFunction linear_function = ecl::blueprints::LinearInterpolation(0.0,1.0,1.0,2.0); + linear_function = LinearFunction::Interpolation(0.0,1.0,1.0,2.0); + std::cout << "Linear function [interpolation]: " << linear_function << std::endl; + linear_function = ecl::blueprints::LinearPointSlopeForm(1.0,3.0,2.0); + linear_function = LinearFunction::PointSlopeForm(1.0,3.0,2.0); + std::cout << "Linear function [point-slope]: " << linear_function << std::endl; + CubicPolynomial cubic; + cubic = ecl::blueprints::CubicDerivativeInterpolation(2.0,0.0,0.0,3.0,1.0,0.0); + cubic = CubicPolynomial::SecondDerivativeInterpolation(1.0,0.0,0.0,2.0,1.0,1.0); // same thing + std::cout << cubic << std::endl; + cubic = CubicPolynomial::DerivativeInterpolation(2.0,0.0,0.0,3.0,1.0,0.0); + std::cout << cubic << std::endl; + QuinticPolynomial quintic; + quintic = QuinticPolynomial::Interpolation(2.0,0.0,0.0,0.0, + 3.0,1.0,0.0,0.0); + std::cout << quintic << std::endl; + std::cout << std::endl; + + std::cout << "Results" << std::endl; + std::cout << string_format("cubic"); + std::cout << string_format("quintic") << std::endl; + for ( int i = 0; i <= 20; ++i ) { + std::cout << format(cubic(2.0 + 0.05*i)); + std::cout << format(quintic(0.0 + 0.05*i)) << std::endl; +// std::cout << format(quintic(0.0 + 0.05*i)) << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Polynomial Derivatives" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Polynomial<2> cubic_derivative = cubic.derivative(); + Polynomial<1> cubic_dderivative = cubic_derivative.derivative(); + + std::cout << "1st Derivative: " << cubic_derivative << std::endl; + std::cout << "2nd Derivative: " << cubic_dderivative << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/pose2d.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/pose2d.cpp new file mode 100644 index 0000000..03d8ac8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/pose2d.cpp @@ -0,0 +1,76 @@ +/** + * @file /src/test/pose2d.cpp + * + * @ingroup UnitTests + * + * Use this to test the pose2d methods. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/geometry/pose2d.hpp" + +/***************************************************************************** +** Conveniences +*****************************************************************************/ + +template +using XYH = ecl::linear_algebra::Matrix; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Pose2D,concatentate) { + XYH pose_b_rel_a, pose_c_rel_b, pose_c_rel_a; + pose_b_rel_a << 1.0, 0.0, ecl::pi / 2.0; + pose_c_rel_b << 1.0, 0.0, - ecl::pi; + pose_c_rel_a << ecl::concatenate_poses(pose_b_rel_a, pose_c_rel_b); + std::cout << "Concatenated Pose: " << pose_c_rel_a.transpose() << std::endl; + + float abs_error = 0.01; + EXPECT_NEAR(1.0, pose_c_rel_a[0], abs_error); + EXPECT_NEAR(1.0, pose_c_rel_a[1], abs_error); + EXPECT_NEAR(- ecl::pi / 2.0, pose_c_rel_a[2], abs_error); +} + +TEST(Pose2D,extend) { + XYH pose, extension; + pose << 1.0, 0.0, ecl::pi / 2.0; + extension << 1.0, 0.0, - ecl::pi; + ecl::extend_pose(pose, extension); + std::cout << "Extended Pose: " << pose.transpose() << std::endl; + + float abs_error = 0.01; + EXPECT_NEAR(1.0, pose[0], abs_error); + EXPECT_NEAR(1.0, pose[1], abs_error); + EXPECT_NEAR(- ecl::pi / 2.0, pose[2], abs_error); +} + +TEST(Pose2D,convenience_class) { + ecl::Pose2D pose(1.0, 0.0, ecl::pi / 2.0); + ecl::Pose2D update(1.0, 0.0, - ecl::pi); + pose *= update; + std::cout << "Pose Operator: " << pose.x() << ", " << pose.y() << ", " << pose.heading() << std::endl; + float abs_error = 0.01; + EXPECT_NEAR(1.0, pose.x(), abs_error); + EXPECT_NEAR(1.0, pose.y(), abs_error); + EXPECT_NEAR(- ecl::pi / 2.0, pose.heading(), abs_error); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/smooth_linear_splines.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/smooth_linear_splines.cpp new file mode 100644 index 0000000..5c15a20 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/smooth_linear_splines.cpp @@ -0,0 +1,95 @@ +/** + * @file /src/test/smooth_linear_splines.cpp + * + * @brief Unit Test for smooth linear splines. + * + * @date July 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "../../include/ecl/geometry/smooth_linear_spline.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::cout; using std::endl; +using std::string; +using ecl::Array; +using ecl::RightAlign; +using ecl::Format; +using ecl::SmoothLinearSpline; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SmoothLinearSplinesTests,allEggsInOneBasket) { + // Haven't got around to running this properly through gtests yet. + SUCCEED(); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + Format string_format; string_format.width(8); string_format.align(RightAlign); + Format format; format.width(8); format.precision(2); format.align(RightAlign); + + /********************* + ** Initialisation + **********************/ + Array x_set(6); + Array y_set(6); + x_set << 0.0, 1.0, 2.0, 3.0, 4.0, 5.0; + y_set << 1.0, 2.0, 1.0, 3.0, 4.0, 4.0; + const double a_max = 10.0; + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Smooth Linear Spline Constructor" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + SmoothLinearSpline spline = SmoothLinearSpline::Interpolation(x_set, y_set, a_max); +// cout << spline_1 << endl; + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Output" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + int n = 200; + cout << string_format("x "); + cout << string_format("y "); + cout << string_format("y' "); + cout << string_format("y''") << endl; + for ( int i = 0; i <= n; ++i ) { + double x = x_set[0] + i*(x_set.back()-x_set.front())/n; + cout << format(x); + cout << format(spline(x)); + cout << format(spline.derivative(x)); + cout << format(spline.dderivative(x)) << endl; + } + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Passed" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_function.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_function.cpp new file mode 100644 index 0000000..d02f42f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_function.cpp @@ -0,0 +1,127 @@ +/** + * @file /src/test/tension_function.cpp + * + * @brief Unit Test for tension functions. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/geometry/tension_function.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::RightAlign; +using ecl::Format; +using ecl::TensionFunction; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TensionFunction,allEggsInOneBasket) { + // Haven't got around to running this properly through gtests yet. + SUCCEED(); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + Format string_format; string_format.width(8); string_format.align(RightAlign); + Format format; format.width(8); format.precision(2); format.align(RightAlign); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructors" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + TensionFunction function; + function = TensionFunction::Interpolation(2.0,1.0,2.0,3.0,2.0,3.0); + + std::cout << "f(tau,x) =" << std::endl; + std::cout << function << std::endl; + + std::cout << string_format("t=0.01"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= 50; ++i ) { + std::cout << format(function(0.01,2.0 + 0.02*i)); + for ( int j = 1; j < 5; j+=1 ) { + std::cout << format(function(1.0*j,2.0 + 0.02*i)); + } + std::cout << format(function(10.0,2.0 + 0.02*i)); + std::cout << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Derivatives" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << string_format("t=0.01"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= 50; ++i ) { + std::cout << format(function.derivative(0.01,2.0 + 0.02*i)); + for ( int j = 1; j < 5; j+=1 ) { + std::cout << format(function.derivative(1.0*j,2.0 + 0.02*i)); + } + std::cout << format(function.derivative(10.0,2.0 + 0.02*i)); + std::cout << std::endl; + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " 2nd Derivatives" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << string_format("t=0.01"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= 50; ++i ) { + std::cout << format(function.dderivative(0.01,2.0 + 0.02*i)); + for ( int j = 1; j < 5; j+=1 ) { + std::cout << format(function.dderivative(1.0*j,2.0 + 0.02*i)); + } + std::cout << format(function.dderivative(10.0,2.0 + 0.02*i)); + std::cout << std::endl; + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_splines.cpp b/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_splines.cpp new file mode 100644 index 0000000..84916bd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_geometry/src/test/tension_splines.cpp @@ -0,0 +1,165 @@ +/** + * @file /src/test/tension_splines.cpp + * + * @brief Unit Test for tension splines. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "../../include/ecl/geometry/tension_spline.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::cout; using std::endl; +using std::string; +using ecl::Array; +using ecl::RightAlign; +using ecl::Format; +using ecl::TensionSpline; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TensionFunctionSplines,allEggsInOneBasket) { + // Haven't got around to running this properly through gtests yet. + SUCCEED(); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + Format string_format; string_format.width(8); string_format.align(RightAlign); + Format format; format.width(8); format.precision(2); format.align(RightAlign); + + /********************* + ** Initialisation + **********************/ + Array x_set(6); + Array y_set(6); + x_set << 0.0, 1.0, 2.0, 3.0, 4.0, 5.0; + y_set << 1.0, 2.0, 1.0, 3.0, 4.0, 4.0; +// Array x_set(5); +// Array y_set(5); +// x_set = 0.0, 0.43, 1, 1.4, 2.86; +// y_set = 0.3, 0.1, -0.27, -0.53, -0.43; + int n = 50; + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Tension Spline Blueprint" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + /********************* + ** Generation + **********************/ + TensionSpline spline_0_1 = TensionSpline::Natural(x_set, y_set, 0.1); + TensionSpline spline_1 = TensionSpline::Natural(x_set, y_set, 1.0); + TensionSpline spline_2 = TensionSpline::Natural(x_set, y_set, 2.0); + TensionSpline spline_3 = TensionSpline::Natural(x_set, y_set, 3.0); + TensionSpline spline_4 = TensionSpline::Natural(x_set, y_set, 4.0); + TensionSpline spline_10 = TensionSpline::Natural(x_set, y_set, 10.0); + cout << spline_1 << endl; + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Output : Splines" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + /********************* + ** Output + **********************/ + std::cout << string_format("t=0.1"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= n; ++i ) { + double x = i*(x_set.back()-x_set.front())/n; + std::cout << format(spline_0_1(x)); + std::cout << format(spline_1(x)); + std::cout << format(spline_2(x)); + std::cout << format(spline_3(x)); + std::cout << format(spline_4(x)); + std::cout << format(spline_10(x)); + std::cout << std::endl; + } + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Output : Derivatives" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + /********************* + ** Output + **********************/ + std::cout << string_format("t=0.1"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= n; ++i ) { + double x = i*(x_set.back()-x_set.front())/n; + std::cout << format(spline_0_1.derivative(x)); + std::cout << format(spline_1.derivative(x)); + std::cout << format(spline_2.derivative(x)); + std::cout << format(spline_3.derivative(x)); + std::cout << format(spline_4.derivative(x)); + std::cout << format(spline_10.derivative(x)); + std::cout << std::endl; + } + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Output : 2nd Derivatives" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + /********************* + ** Output + **********************/ + std::cout << string_format("t=0.1"); + std::cout << string_format("t=1"); + std::cout << string_format("t=2"); + std::cout << string_format("t=3"); + std::cout << string_format("t=4"); + std::cout << string_format("t=10") << std::endl; + for ( int i = 0; i <= n; ++i ) { + double x = i*(x_set.back()-x_set.front())/n; + std::cout << format(spline_0_1.dderivative(x)); + std::cout << format(spline_1.dderivative(x)); + std::cout << format(spline_2.dderivative(x)); + std::cout << format(spline_3.dderivative(x)); + std::cout << format(spline_4.dderivative(x)); + std::cout << format(spline_10.dderivative(x)); + std::cout << std::endl; + } + + cout << endl; + cout << "***********************************************************" << endl; + cout << " Passed" << endl; + cout << "***********************************************************" << endl; + cout << endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_ipc/.cproject b/ros2_ws/src/ecl_core/ecl_ipc/.cproject new file mode 100644 index 0000000..546a7bb --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/.cproject @@ -0,0 +1,251 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + true + true + true + + + make + + all + true + true + true + + + make + + tests + true + true + true + + + make + + test + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/.project b/ros2_ws/src/ecl_core/ecl_ipc/.project new file mode 100644 index 0000000..5835bc8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/.project @@ -0,0 +1,78 @@ + + + ecl_ipc + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_ipc/CHANGELOG.rst new file mode 100644 index 0000000..c0c9a70 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/CHANGELOG.rst @@ -0,0 +1,19 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_ipc +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.61.12 (2016-05-03) +-------------------- +* minor bugfix for includes on apple osx + +0.60.8 (2014-02-10) +------------------- +* ecl_ipc requires ecl_build for cmake modules. +* make sure we detect threads in this module +* Contributors: Daniel Stonier + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_ipc/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/CMakeLists.txt new file mode 100644 index 0000000..761f290 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/CMakeLists.txt @@ -0,0 +1,59 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_ipc) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_time_lite REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_threads REQUIRED) +find_package(ecl_time REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() +ecl_detect_threads() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors + ecl_exceptions + ecl_threads + ecl_time_lite + ecl_time +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_ipc/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_ipc/doxygen/mainpage.dox new file mode 100644 index 0000000..db51da5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/doxygen/mainpage.dox @@ -0,0 +1,142 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Interprocess mechanisms vary substantially across operating systems, though thankfully + most support the traditional posix which is also often referred to now as the + Single Unix Specification V3 (SUSV3). Nevertheless, where there are differences, the + setup will allow abstractions around these so as to provide a single cohesive interface + to the interprocess mechanisms. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + using ecl::Semaphore; + using ecl::SharedMemory; + @endcode + + You will also need to link to -lecl_ipc. + +\section usage Usage + + @subsection sharedMemorySection SharedMemory + + Used in conjunction with semaphores, shared memory sections provide the + fastest way for processes to directly communicate with each other. + Usually you reserve a block and then cast in and out of the direct + memory addresses allocated within the reserved memory. However, this is not + typesafe and error-prone, so the shared memory wrapper here instead + allocates a block that is implicitly tied to a data structure. The following + steps provide an easy, convenient way to access the reserved memory + block through a typesafe and well-structured api. + + - Formulate a data structure of fixed size. + - Create a wrapper class that includes a semaphore, shared memory object, a read/write interface and pointer to the data. + - Instantiate the shared memory using with the data structure as a template argument. + - Point to the data section stored in the shared memory. + - Initialise the data section (if its the first accessor). + - Establish the read/write interface which will internally use semaphores to access the shared memory. + + @code + struct DataStructure { + int i; + }; + class Data { + public: + void readInteger(int i); + void writeInteger(int j); + + private: + void initialise(); + + SharedMemory< DataStructure > sm; + Semaphore semaphore; + DataStructure *data; + }; + + inline Data::Data() : sm("sm_test"), semaphore("sem_test"), data(NULL) { + data = sm.data(); + initialise(); + } + inline Data::readInteger(int i) { + semaphore.lock(); + i = data->i; + semaphore.unlock(); + } + inline Data::writeInteger(int i) { + semaphore.lock(); + data->i = i; + semaphore.unlock(); + } + @endcode + + Note, ensure you do not use variable length types (such as stl containers) inside the data structure + because the shared memory section allocates memory based on the initial size of the data structure. + + Also note, initialisation and closure can be a little complicated. With initailisation, you want to ensure that only + the first accessor blanks the memory, but there is no way of guaranteeing via the shared memory class that + you're the first accessor - in some cases you could be accessing an already reserved block. One way + of getting around this is to set a magic number in the data structure and see if that reads rubbish when + you initialise. If it does - then appropriately initialise all you data structure variables and set your + magic number accordingly - subsequent accesses from different processes should find the correct magic number and not initialise. + + With regards to closure, there is no guarantee that you can actually clean up the memory block. If everything + runs fine and closes without error, then it will be fine, but if your program crashes in some unforeseen way + and not all of the operating system signals are set up (usually too much detail to bother with), then + the memory block will remain on the system. Often its easier to get some external script to clean the + memory sections. + + @subsection Semaphores + + There are many ways to implement semaphores (especially the + counting semaphores on posix), but I've kept it relatively + simple here with the task at hand being just to provide a lock that + can be used when accessing shared memory. Its usage is very similar to + thread mutexes with the only difference being the instantiation via a string identifier + (similar to the case for shared memory). Note, on windows semaphores + are usually referred to as mutexes (confusing!). + + @code + //...First process + Semaphore semaphore("test_sem"); + semaphore.lock(); + // ... access shared memory here + semaphore.unlock(); + + //...Second process + Semaphore semaphore("test_sem"); + semaphore.lock(); + // ... access shared memory here + semaphore.unlock(); + @endcode + + If another semaphore (doesn't have to be the same object, just a semaphore + instantiated from the same name) tries to lock an already locked semaphore, + it will wait until the first semaphore releases the lock. Be wary of + deadlocks. + +\section unitTests Unit Tests + + - src/test/semaphores.cpp + - src/test/semaphores_timed.cpp + - src/test/shared_memory.cpp + +\section ToDo + + Could use some fallback for error handling when exceptions are disabled. + +\section ChangeLog + + - May 11 : Updated with better posix and exception handling. + - Mar 11 : Moved process priorities to threads. + - May 09 : Posix @ref ecl::SharedMemory "shared memory" structures. + - May 09 : Binary process locks via posix @ref ecl::Semaphore "semaphores". + - May 09 : Posix static methods for process handling. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_ipc/doxygen/namespaces.dox new file mode 100644 index 0000000..a12aa71 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/doxygen/namespaces.dox @@ -0,0 +1,15 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::ipc + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..062ac43 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ipc) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc.hpp b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc.hpp new file mode 100644 index 0000000..b253684 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc.hpp @@ -0,0 +1,32 @@ +/** + * @file /include/ecl/ipc.hpp + * + * @brief Cross-platform inter-process communication mechanisms. + * + * @date May, 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IPC_HPP_ +#define ECL_IPC_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#ifdef emit + #undef emit + #define replace_qt_emit +#endif + +#include "ipc/semaphore.hpp" +#include "ipc/shared_memory.hpp" + +#ifdef replace_qt_emit + #define emit +#endif + +#endif /*ECL_IPC_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/CMakeLists.txt new file mode 100644 index 0000000..e857373 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/ipc) + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore.hpp b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore.hpp new file mode 100644 index 0000000..558aae7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore.hpp @@ -0,0 +1,34 @@ +/** + * @file /include/ecl/ipc/semaphore.hpp + * + * @brief Provides a class for securing shared data between processes. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IPC_SEMAPHORE_HPP_ +#define ECL_IPC_SEMAPHORE_HPP_ + +/***************************************************************************** +** Platform Detection +*****************************************************************************/ + +#include // ECL_ macros + +/***************************************************************************** +** Cross Platform Implementation +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #ifdef _POSIX_SEMAPHORES + #if _POSIX_SEMAPHORES > 0 + #include "semaphore_pos.hpp" + #endif + #endif +#endif + + +#endif /*ECL_IPC_SEMAPHORE_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore_pos.hpp b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore_pos.hpp new file mode 100644 index 0000000..d149c13 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/semaphore_pos.hpp @@ -0,0 +1,204 @@ +/** + * @file /include/ecl/ipc/semaphore_pos.hpp + * + * @brief The posix implementation for semaphores. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IPC_SEMAPHORE_POS_HPP_ +#define ECL_IPC_SEMAPHORE_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) +#include +#ifdef _POSIX_SEMAPHORES +#if _POSIX_SEMAPHORES > 0 + +/***************************************************************************** +** Ecl Functionality Defines +*****************************************************************************/ + +#ifndef ECL_HAS_POSIX_SEMAPHORES + #define ECL_HAS_POSIX_SEMAPHORES +#endif +#ifndef ECL_HAS_SEMAPHORES + #define ECL_HAS_SEMAPHORES +#endif + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include /* For O_* constants */ +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +class Semaphore; + +#ifdef ECL_HAS_EXCEPTIONS + +namespace ipc { + +/***************************************************************************** +** Semaphore Exceptions +*****************************************************************************/ +/** + * This static function generates a custom StandardException response + * for posix error numbers generated by sem_open calls within + * the Semaphore class. Relevant man page is: + * + * - sem_open + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +ECL_LOCAL ecl::StandardException openSemaphoreException(const char* loc ); +/** + * This static function generates a custom StandardException response + * for posix error numbers generated by sem_trywait calls within + * the Semaphore class. Relevant man page is: + * + * - sem_trywait + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +ECL_LOCAL ecl::StandardException tryLockSemaphoreException(const char* loc); + +} // namespace ipc + +#endif /* ECL_HAS_EXCEPTIONS */ + +/***************************************************************************** +** Semaphores +*****************************************************************************/ +/** + * @brief Inter-process locking mechanism for securing shared data. + * + * Secures data stored in shared memory via a mutual exclusion style + * construction. There are other uses for semaphores, and alot more + * complexity that can be taken advantage of. However this class' intention + * remains simple, if such complexity is needed, other semaphore wrappers + * will be created. + * + * Note: windows calls this a Mutex + * which is slightly confusing - the windoze mutex is simply a binary + * version of the posix semaphore). + * + * Usage should be easy to ascertain after glancing at the Semaphore + * interface. + **/ +class ECL_PUBLIC Semaphore +{ +public: + /********************* + ** C&D's + **********************/ + /** + * @brief Default constructor (always throws). + * + * This is a pure RAII style object and subsequently will always throw. + * + * @exception StandardException : automatically throws if used. + */ + Semaphore(); + /** + * @brief Initialises a connection to a semaphore. + * + * RAII style constructor that creates (if not already existing) + * and opens a connection to a semaphore with + * the specified string identifier (do not use any '/'s or special characters). + * Note that this automatically prepends a '/' to create a posix semaphore name. + * + * @param string_id : unique string identifier for the shared memory (no slashes) + * + * @exception StandardException : throws if the semaphore didn't initialise properly [debug mode only]. + */ + Semaphore(const std::string& string_id); + /** + * @brief Clean up the semaphore handles. + * + * Cleans up the posix structures associated with the semaphore. + **/ + virtual ~Semaphore(); + + /********************* + ** Locking + **********************/ + /** + * @brief Lock the semaphore. + * + * Lock access to the semaphore. If already locked, wait for it to unlock before locking. + **/ + void lock(); + /** + * @brief Unlock the semaphore. + * + * Unlock the semaphore. + **/ + void unlock(); + /** + * @brief Only lock the semaphore if currently unlocked. + * + * This attempts to lock the semaphore, but will not wait around if it is already locked. + * @return bool : success or failure to lock the semaphore. + */ + bool trylock(); + /** + * @brief Only lock the semaphore if it can before the timeout occurs. + * + * Try locking the semaphore over the specified duration. + * This duration is a relative time period (starting from + * the instant this function is called). + * + * Note: this function is not always available on posix systems (e.g. macosx). + * When it is not present, it will simply default its behaviour to that of a + * regular trylock(). + * + * @param timeout : stop trying to lock if the timeout is reached. + * + * @exception StandardException : throws if locking attempt aborted (other than timeouts) [debug mode only]. + **/ + bool trylock( const Duration &timeout ); + +private: + std::string name; + sem_t* semaphore; + + /** + * @brief Return the semaphore count. + * + * This is not transparent to the user of the class as the semaphore here + * functions simply as a binary lock to shared memory. It is used however internally. + **/ + int count(); +}; + + +} // namespace ecl + + +#endif /* _POSIX_SEMAPHORES > 0 */ +#endif /* _POSIX_SEMAPHORES */ +#endif /* ECL_IS_POSIX */ + +#endif /* ECL_IPC_SEMAPHORE_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory.hpp b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory.hpp new file mode 100644 index 0000000..fa73697 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory.hpp @@ -0,0 +1,34 @@ +/** + * @file /include/ecl/ipc/shared_memory.hpp + * + * @brief Provides a class for sharing data between processes. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IPC_SHARED_MEMORY_HPP_ +#define ECL_IPC_SHARED_MEMORY_HPP_ + +/***************************************************************************** +** Platform Detection +*****************************************************************************/ + +#include // ECL_ macros + +/***************************************************************************** +** Cross Platform Implementation +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #ifdef _POSIX_SHARED_MEMORY_OBJECTS + #if _POSIX_SHARED_MEMORY_OBJECTS > 0 + #include "shared_memory_pos.hpp" + #endif + #endif +#endif + + +#endif /*ECL_IPC_SHARED_MEMORY_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory_pos.hpp b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory_pos.hpp new file mode 100644 index 0000000..88f8894 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/include/ecl/ipc/shared_memory_pos.hpp @@ -0,0 +1,255 @@ +/** + * @file /include/ecl/ipc/shared_memory_pos.hpp + * + * @brief The posix implementation for shared memory. + * + * Requires _POSIX_SHARED_MEMORY_OBJECTS + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IPC_SHARED_MEMORY_RT_HPP_ +#define ECL_IPC_SHARED_MEMORY_RT_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) +#include +#if !defined(ECL_IS_APPLE) +#include +#endif +#ifdef _POSIX_SHARED_MEMORY_OBJECTS +#if _POSIX_SHARED_MEMORY_OBJECTS > 0 + +/***************************************************************************** +** Ecl Functionality Defines +*****************************************************************************/ + +#ifndef ECL_HAS_POSIX_SHARED_MEMORY + #define ECL_HAS_POSIX_SHARED_MEMORY +#endif +#ifndef ECL_HAS_SHARED_MEMORY + #define ECL_HAS_SHARED_MEMORY +#endif + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include /* For shm_open() */ +#include /* For O_* constants */ +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Exception Handling +*****************************************************************************/ + +namespace ipc { + +#ifndef ECL_DISABLE_EXCEPTIONS +/** + * @brief Posix exception handler for opening shared memory. + * + * This function generates a custom StandardException response + * for posix error numbers generated by open requests within + * the SharedMemory class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +// Have to be public since its called from a template (inline) function. +ECL_PUBLIC ecl::StandardException openSharedSectionException(const char* loc); +/** + * @brief Posix exception handler for shared memory mappings. + * + * This function generates a custom StandardException response + * for posix error numbers generated by memory mapping calls within + * the SharedMemory class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +ECL_PUBLIC ecl::StandardException memoryMapException(const char* loc); +#endif + +/** + * @brief Common shared memory functions wrapping the underlying rt calls. + * + * This is a bit of magic to make sure that the rt calls are always + * called in the implementation (cpp files). This way the library doesn't + * get underlinked for rt. + */ +class ECL_PUBLIC SharedMemoryBase { +public: + /** + * @brief Unlink the memory. + * + * Mapped processes may still use, but no new objects can connect to it. + **/ + void unlink(); + +protected: + SharedMemoryBase(const std::string &name_id) : + name(name_id), + shared_memory_manager(false) + {}; + /** + * @brief Open and configure the shared memory. + * + * Does a fair bit of automatic configuration here. + * + * @return int : -1 is a fail, success is anything else. + */ + int open(); + + std::string name; + bool shared_memory_manager; +}; + +} // namespace ipc + +/***************************************************************************** +** Shared Memory +*****************************************************************************/ +/** + * @brief Templatised interface for shared memory. + * + * Templatises the interface for shared memory by representing the + * storage area by the templatised data type. + * + * The templatised data type must be a type that has a fixed size as it + * is its own size that determines the size of the storage area. Be + * careful about using stl containers (strings, vectors etc). Even if + * you fix their capacity, I'm not yet sure how they will behave. + **/ +template +class ECL_PUBLIC SharedMemory : public ipc::SharedMemoryBase +{ +public: + /********************* + ** C&D's + **********************/ + SharedMemory(const std::string& string_id); + virtual ~SharedMemory(); + + Storage* data() { return storage; } /**< Data storage accessor. **/ + +private: + SharedMemory() {} /**< @brief Default constructor - use is forbidden. **/ + const int shared_memory_size; + Storage *storage; +}; + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +/** + * @brief RIAA style shared memory initialiser. + * + * Configures the shared memory with the given pathname and if it + * is created (not already existing), it uses a default storage structure (Storage()) + * to initialise shared memory region. + * + * @param string_id : unique string identifier for the shared memory (no slashes) + * + * @exception StandardException : throws if the shared memory could not be initialised. + **/ +template +SharedMemory::SharedMemory(const std::string& string_id ) : + ipc::SharedMemoryBase(std::string("/")+string_id), + shared_memory_size(sizeof(Storage)), + storage(NULL) +{ + int shm_descriptor = open(); + if ( shm_descriptor == -1) { + ecl_throw( ipc::openSharedSectionException(LOC) ); + } + /********************* + * Mapping + *********************/ + /* + * Map the shared memory into your process's address space. + * + * Address: 0 lets posix choose the address. + * Memory Protections: PROT_READ,WRITE,EXEC,NONE. Tells the MMU what to do. Match with the shm_open parameters. + * PROT_EXEC only useful if you want to run a shared library there. + * Mapping Flags: Always choose MAP_SHARED for shared memory! Other options almost irrelevant. + * Descriptor : shm_send_descriptor from above. + * OFFSET : we should never really want to offset a chunk of memory. Just point it at the start (0). + * + * mmap(address,sharedMemSize,memprotections,mappingflags,descriptor,offset); + */ + void * shm_address; + if ( (shm_address = mmap(0,shared_memory_size,PROT_READ|PROT_WRITE,MAP_SHARED,shm_descriptor,(long) 0)) == MAP_FAILED ) + { + shared_memory_manager = false; + close(shm_descriptor); + unlink(); + ecl_throw( ipc::memoryMapException(LOC) ); + } + /* + * When first created, the shared memory has 0 size. You need to inflate it before + * you can use it. The second argument, the length is measured in bytes. + */ + if ( ftruncate(shm_descriptor,shared_memory_size) < 0 ) + { + shared_memory_manager = false; + close(shm_descriptor); + unlink(); + ecl_throw(StandardException(LOC,OpenError,"Shared memory created, but inflation to the desired size failed.")); + } + + /********************* + ** Close + **********************/ + /* + * This does not unmap the memory allocated to the block. It just closes the file + * descriptor. Should do it early for tidiness if for no other reason. + */ + close(shm_descriptor); + + storage = (Storage*) shm_address; + + // If just allocated, initialise the shared memory structure. + if ( shared_memory_manager ) { + *storage = Storage(); + } +} +/** + * Default destructor. Closes the file descriptor and unlinks the name so that no-one else + * can open into the shared memory. Once all processes finish with it, the shared memory + * disintegrates. + **/ +template +SharedMemory::~SharedMemory() +{ + /* Might be worth putting a check on this later (i.e. < 0 is an error). */ + munmap( (void*) storage,shared_memory_size); +// munmap(shm_address,shared_memory_size); + + if ( shared_memory_manager ) { + unlink(); + } +} + +} // namespace ecl + + +#endif /* _POSIX_SHARED_MEMORY_OBJECTS > 0 */ +#endif /* _POSIX_SHARED_MEMORY_OBJECTS */ +#endif /* ECL_IS_POSIX */ + +#endif /* ECL_IPC_SHARED_MEMORY_RT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/package.xml b/ros2_ws/src/ecl_core/ecl_ipc/package.xml new file mode 100644 index 0000000..dc561c3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/package.xml @@ -0,0 +1,48 @@ + + + ecl_ipc + 1.2.1 + + Interprocess mechanisms vary greatly across platforms - sysv, posix, win32, there + are more than a few. This package provides an infrastructure to allow for developing + cross platform c++ wrappers around the lower level c api's that handle these + mechanisms. These make it not only easier to utilise such mechanisms, but allow it + to be done consistently across platforms. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_ipc + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_threads + ecl_time_lite + ecl_time + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_threads + ecl_time_lite + ecl_time + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/src/CMakeLists.txt new file mode 100644 index 0000000..efc866b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# Subdirectories +############################################################################### + +if(ECL_PLATFORM_HAS_POSIX_THREADS) + add_subdirectory(lib) +endif() + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/CMakeLists.txt new file mode 100644 index 0000000..cacf31e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/CMakeLists.txt @@ -0,0 +1,44 @@ +############################################################################### +# SOURCES +############################################################################### + +SET(SOURCES + semaphore_pos.cpp + shared_memory_pos.cpp +) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_threads::ecl_threads + ecl_time_lite::ecl_time_lite + ecl_time::ecl_time +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/lib/semaphore_pos.cpp b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/semaphore_pos.cpp new file mode 100644 index 0000000..7a8291a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/semaphore_pos.cpp @@ -0,0 +1,247 @@ +/** + * @file /src/lib/semaphore_pos.cpp + * + * @brief Posix semaphore implementation. + * + * @date August 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/ipc/semaphore_pos.hpp" + +#ifdef ECL_HAS_POSIX_SEMAPHORES + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using std::ostringstream; + +/***************************************************************************** +** Implementation [Semaphore] +*****************************************************************************/ + +Semaphore::Semaphore() { + // Never use this constructor + throw StandardException(LOC, RaiiError); +} + +Semaphore::Semaphore(const std::string& string_id): + name(string("/"+string_id)), + semaphore(NULL) +{ + /********************* + * Open Flags + *********************/ + /* + * O_CREAT : it will try and create a semaphore or just open if it already exists + * O_EXCL : when used with O_CREAT fails to open if the semaphore already exists. + * + * Other flags are unnecessary. + */ + static const int open_flags = O_CREAT; + /********************* + * Permissions + *********************/ + /* + * Permissions. Must be specified when O_CREAT is used, otherwise it is ignored. It + * is combined with the process umask (permissions & ~umask). + * S_IRWXU [00700] - read, write & exec by user + * S_IRUSR [00400] - read by the user who owns it + * S_IWUSR [00200] - write by user + * S_IXUSR [00100] - exec by user + * S_IRWXG [00070] - read, write & exec by group + * S_IRGRP [00040] - read by group + * S_IWGRP [00020] - write by group + * S_IXGRP [00010] - exe by group + * S_IRWXG [00007] - read, write & exec by other + * S_IROTH [00004] - read by other + * S_IWOTH [00002] - write by other + * S_IXOTH [00001] - exe by other + * + * Semaphores just have access, or they do not (p.137 of the posix bible). Just + * set rwx on whichever subset of users applies. As we're not worried about + * security here, just open them up. + */ + static const int permissions = S_IRWXU|S_IRWXG|S_IRWXO; + /* + * The initial value of the semaphore. For mutex style semaphores, set the + * initial value to be unlocked. + */ + static const int initial_value_unlocked = 1; + + /********************* + ** Open + **********************/ + semaphore = sem_open(name.c_str(),open_flags,permissions,initial_value_unlocked); + ecl_assert_throw(semaphore != SEM_FAILED, ipc::openSemaphoreException(LOC)); +} + +Semaphore::~Semaphore() +{ + // Should check the error, but only fails if the semaphore is invalid (checked by constructor). + sem_close(semaphore); + // Should check the error, but only fails with noncritical errors. + sem_unlink(name.c_str()); +} + +void Semaphore::lock() +{ + sem_wait(semaphore); +} + +int Semaphore::count() +{ + // Should check the error, but only fails if the semaphore is invalid (checked by constructor). + int semaphore_count; + sem_getvalue(semaphore,&semaphore_count); + return semaphore_count; +} + +void Semaphore::unlock() +{ + // Should check the error, but only fails if the semaphore is invalid (checked by constructor). + // The other error is an overflow error, which is handled by constraining our count to 1. + if ( count() == 1 ) { // Already unlocked + return; + } else { + sem_post(semaphore); + } +} + +bool Semaphore::trylock() +{ + // 0 is a success + if ( sem_trywait( semaphore ) == 0 ) { + return true; + } else { + // Should check errno = EAGAIN for implication that a locked semaphore caused it to fail + // and not something else + return false; + } +} + +bool Semaphore::trylock( const Duration &timeout ) { + + #if defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS - 200112L) >= 0L + long tnsec; + timespec ctime; + + if ( epoch_time(ctime).flag() != NoError ) { return false; } + + ctime.tv_sec += timeout.sec(); + + tnsec = ctime.tv_nsec + timeout.nsec(); + if(tnsec >= 999999999 ) { ctime.tv_sec += 1; } + tnsec %= 1000000000; + ctime.tv_nsec = tnsec; + + // We already guarantee timeout is the right structure, so no + // need to check for EINVAL, other errors should be almost + // irrelevant for us too. + int result = sem_timedwait( semaphore, &ctime ); + if ( result != 0 ) { + if ( errno == ETIMEDOUT ) { + // The timeout kicked in + return false; + } else { + ecl_debug_throw( ipc::tryLockSemaphoreException(LOC)); + // either a signal interrupt EINTR + // or a blocking (when does this occur? EAGAIN + return false; + } + } + #else + return trylock(); // fallback to standard trylock + #endif + return true; +} + +/***************************************************************************** +** Exception Handlers +*****************************************************************************/ + +#ifdef ECL_HAS_EXCEPTIONS + +namespace ipc { + +ecl::StandardException openSemaphoreException(const char* loc) { + int error_result = errno; + switch ( error_result ) { + case ( EACCES ) : { + return StandardException(LOC,PermissionsError,"The semaphore exists, but permission to open has been denied."); + } + case ( EEXIST ) : { + return StandardException(LOC,PermissionsError,"The semaphore already exists, so your request to explicitly create was denied."); + } + case ( ENOENT ) : { + return StandardException(LOC,ConfigurationError,"The semaphore requested doesn't already exist (you specifically requested it to just open, not create)."); + } + case ( ENOMEM ) : { + return StandardException(LOC,MemoryError,"Insufficient memory."); + } + case ( EINVAL ) : { + return StandardException(LOC,InvalidArgError,"Name was empty (i.e. '/'). Can also be the maximum number of semaphores has already been exceeded."); + } + case ( EMFILE ) : { + return StandardException(LOC,OutOfResourcesError,"This process has already exceeded the number of files/pseudofiles it is permitted to open."); + } + case ( ENFILE ) : { + return StandardException(LOC,OutOfResourcesError,"This system has already exceeded the number of files/pseudofiles it is permitted to open."); + } + case ( ENAMETOOLONG ) : { + return StandardException(LOC,InvalidArgError,"The semaphore name was too long."); + } + default : + { + ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +ecl::StandardException tryLockSemaphoreException(const char* loc) { + int error_result = errno; + switch ( error_result ) { + case ( EINTR ) : { + return StandardException(LOC,InterruptedError,"Waiting for the semaphore lock was interrupted by a system signal."); + } + case ( EINVAL ) : { + return StandardException(LOC,InvalidArgError,"The semaphore was invalid or the timeout structure specified was invalid."); + } + case ( EAGAIN ) : { + return StandardException(LOC,BlockingError,"The waiting operation could not be performed without blocking???"); + } + default : + { + ostringstream ostream; + ostream << "Posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +} // namespace ipc + +#endif /* ECL_HAS_EXCEPTIONS */ + +} // namespace ecl + +#endif /* ECL_HAS_POSIX_SEMAPHORES */ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/lib/shared_memory_pos.cpp b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/shared_memory_pos.cpp new file mode 100644 index 0000000..7430e0b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/lib/shared_memory_pos.cpp @@ -0,0 +1,185 @@ +/** + * @file /ecl_ipc/src/lib/shared_memory_pos.cpp + * + * @brief Magic trick to make sure the library is called for shared memory. + * + * If using --as-needed and shared memory objects, this library will often + * not get called (as the shared memory class is 100% headers). This will + * result in sometimes (if nothing else calls it) -lrt not being called + * and ultimately you will get undefined references to shm_unlink and co. + * + * This is some magic to make sure that you always bring in the library + * when using the shared memory class. + * + * @date January 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + + +#include "../../include/ecl/ipc/shared_memory_pos.hpp" + +#ifdef ECL_HAS_POSIX_SHARED_MEMORY + +#include +#include /* For shm_open() */ +#include /* For O_* constants */ +#include +#include +#include +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace ipc { + +void SharedMemoryBase::unlink() { + shm_unlink(name.c_str()); +} + +int SharedMemoryBase::open() { + /********************* + * Open Flags + *********************/ + /* + * O_CREAT : it will try and create some memory or just open if it already exists + * if the shared memory object already exists. + * O_EXCL : when used with O_CREAT fails to open if the message queue already exists. + * : if neither, then it will only open an existing memory. + * O_WRONLY : write only. + * O_RDONLY : read only. + * O_RDWR : read-write. + * O_NONBLOCK : normally it will block if sending to a full queue. Disable this. + */ + static const int open_flags = O_RDWR; + static const int create_flags = O_CREAT|O_RDWR|O_EXCL; + /********************* + * Permissions + *********************/ + /* + * Permissions. Must be specified when O_CRELOC is used, otherwise it is ignored. It + * is combined with the process umask (permissions & ~umask). + * S_IRWXU [00700] - read, write & exec by user + * S_IRUSR [00400] - read by the user who owns it + * S_IWUSR [00200] - write by user + * S_IXUSR [00100] - exec by user + * S_IRWXG [00070] - read, write & exec by group + * S_IRGRP [00040] - read by group + * S_IWGRP [00020] - write by group + * S_IXGRP [00010] - exe by group + * S_IRWXG [00007] - read, write & exec by other + * S_IROTH [00004] - read by other + * S_IWOTH [00002] - write by other + * S_IXOTH [00001] - exe by other + */ + static const int permissions = S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH; + /************************************************************************* + ** Name + *************************************************************************/ + /* + * The name is like a filename. To be compatible on all systems, always + * begin with a leading '/' and include no other '/'s. + * In debug mode, might be worth parsing the name here. + */ + /************************************************************************* + ** Open + *************************************************************************/ + int shm_descriptor = shm_open(name.c_str(),create_flags,permissions); + if ( ( shm_descriptor == -1 ) && ( errno == EEXIST ) ) { + // Maybe its already open, try opening it normally + shm_descriptor = shm_open(name.c_str(),open_flags,permissions); + } else { + shared_memory_manager = true; + } + if ( shm_descriptor == -1) { + } + return shm_descriptor; +} + + +/***************************************************************************** +** Exception Handlers +*****************************************************************************/ + +#ifndef ECL_DISABLE_EXCEPTIONS + +ecl::StandardException openSharedSectionException(const char* loc) { + int error_result = errno; + switch (error_result) { + case ( EACCES ) : { + throw StandardException(LOC,PermissionsError,"Opening shared memory failed - permission denied."); + break; + } + // case ( EEXIST ) : { // If using O_EXCL, need this, otherwise no. + // // pathname exists, assume its a fifo and continue + // break; + // } + case ( EMFILE ) : case ( ENFILE ) : { + throw StandardException(LOC,OutOfResourcesError,"Opening shared memory failed - too many file connections already open."); + break; + } + case ( ENOENT ) : case ( ENAMETOOLONG ) : case ( EINVAL ) : { + throw StandardException(LOC,InvalidArgError,"Opening shared memory failed - pathname problem."); + break; + } + case ( ENOSYS ) : { + throw StandardException(LOC,NotSupportedError,"Opening shared memory failed - kernel system functions are not available (remake the kernel)."); + break; + } + default : + { + std::ostringstream ostream; + ostream << "Posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + +ecl::StandardException memoryMapException(const char* loc) { + int error_result = errno; + switch (error_result) { + case ( EACCES ) : { + return StandardException(LOC,PermissionsError,"Shared mapping failed - permission problems (see man mmap)."); + } + case ( EAGAIN ) : { + return StandardException(LOC,MemoryError,"Shared mapping failed - file locked or too much memory has been locked."); + } + case ( EBADF ) : { + return StandardException(LOC,InvalidArgError,"Shared mapping failed - not a valid file descriptor (see man mmap)."); + } + case ( EINVAL ) : { + return StandardException(LOC,InvalidArgError,"Shared mapping failed - start, length or offset were invalid or MAP_PRIVLOCE and MAP_SHARED were either both present or both obso (see man mmap)."); + } + case ( ENFILE ) : { + return StandardException(LOC,OutOfResourcesError,"Shared mapping failed - system limit on the total number of open files has been reached (see man mmap)."); + } + case ( ENODEV ) : { + return StandardException(LOC,NotSupportedError,"Shared mapping failed - underlying filesystem of the specified file doesn't support memory mapping (see man mmap)."); + } + case ( ENOMEM ) : { + return StandardException(LOC,MemoryError,"Shared mapping failed - no mem available, or max mappings exceeded (see man mmap)."); + } + case ( EPERM ) : { + return StandardException(LOC,PermissionsError,"Shared mapping failed - EPERM (see man mmap)."); + } +// case ( ETXBSY ) : { +// return StandardException(LOC,"Shared mapping failed.","ETXBSY (see man mmap)."); +// break; +// } + default : + { + std::ostringstream ostream; + ostream << "Posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} +#endif /* ECL_DISABLE_EXCEPTIONS */ + +} // namespace ipc +} // namespace ecl + +#endif /* ECL_HAS_POSIX_SHARED_MEMORY */ diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_ipc/src/test/CMakeLists.txt new file mode 100644 index 0000000..e05a9cc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/test/CMakeLists.txt @@ -0,0 +1,24 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_ipc_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries( + ecl_test_${test_name} + ${PROJECT_NAME} + ecl_exceptions::ecl_exceptions + ecl_time::ecl_time + ) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_ipc_add_gtest(shared_memory) +ecl_ipc_add_gtest(semaphores) +ecl_ipc_add_gtest(semaphores_timed) + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores.cpp b/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores.cpp new file mode 100644 index 0000000..7985b4a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores.cpp @@ -0,0 +1,183 @@ +/** + * @file /src/test/semaphores.cpp + * + * @brief Unit Test for semaphores. + * + * @date August 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/ipc/semaphore.hpp" +#include "../../include/ecl/ipc/shared_memory.hpp" + +#ifdef ECL_HAS_SEMAPHORES + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::SharedMemory; +using ecl::Semaphore; +using ecl::Sleep; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace ipc { +namespace tests { + +/***************************************************************************** +** Data Storage Class +*****************************************************************************/ + +class SemaphoreTestData { + public: + double value[2]; + void initialise() { value[0] = 1.0; value[1] = 2.0; }; +}; + +} // namespace tests +} // namespace ipc +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::ipc::tests::SemaphoreTestData; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @endcond + */ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SemaphoreTests,access) { + + string sm_name("shared_memory"); + string sem_name("shared_semaphore"); + Sleep sleep; + + pid_t pID = fork(); + if (pID == 0) + { + /********************************************************************* + ** Child + *********************************************************************/ + sleep(1); + try { + SharedMemory sm(sm_name); + Semaphore semaphore(sem_name); +// std::cout << "Child waiting" << std::endl; +// std::cout << "Child trying the lock" << std::endl; + if ( !semaphore.trylock() ) { +// std::cout << "Child tried the lock but failed, now hard locking" << std::endl; + semaphore.lock(); + } +// std::cout << "Child entering shared memory" << std::endl; + SemaphoreTestData *data = sm.data(); +// std::cout << "Child: " << data->value[0] << " " << data->value[1] << std::endl; + EXPECT_EQ(1.3,data->value[0]); + EXPECT_EQ(2.3,data->value[1]); + semaphore.unlock(); + } catch ( ecl::StandardException &e) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } + else if (pID < 0) // failed to fork + { + std::cerr << "Failed to fork" << std::endl; + exit(1); + } + else + { + /********************************************************************* + ** Parent + *********************************************************************/ + try { + SharedMemory sm(sm_name); + Semaphore semaphore(sem_name); + SemaphoreTestData *data = sm.data(); + semaphore.lock(); +// std::cout << "Parent in the shared memory" << std::endl; + sleep(2); + data->value[0] = 1.3; + data->value[1] = 2.3; + EXPECT_EQ(1.3,data->value[0]); + EXPECT_EQ(2.3,data->value[1]); +// std::cout << "Parent: " << data->value[0] << " " << data->value[1] << std::endl; +// std::cout << "Parent leaving shared memory" << std::endl; + semaphore.unlock(); + sleep(3); + } catch ( ecl::StandardException &e) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } + SUCCEED(); + +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << std::endl; + std::cout << "What you should see:" << std::endl; + std::cout << " - Process forks" << std::endl; + std::cout << " - Parent creates shared memory." << std::endl; + std::cout << " - Parent locks a semaphore and enters shared memory for 2 seconds." << std::endl; + std::cout << " - Child waits one second and attempts to lock the already locked semaphore." << std::endl; + std::cout << " - Parent writes into shared memory and unlocks the semaphore." << std::endl; + std::cout << " - Child finally gains access and reads the shared memory." << std::endl; + std::cout << " - Parent process sleeps for four seconds while child dies." << std::endl; + std::cout << " - Parent dies." << std::endl; + std::cout << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +#else + +/***************************************************************************** +** Alternative Main +*****************************************************************************/ + +int main(int /* argc */, char ** /* argv */) { + std::cout << std::endl; + std::cout << "Semaphores are not supported on this platform (or ecl is just lacking)." << std::endl; + std::cout << std::endl; + return 0; +} + +#endif /* ECL_HAS_SEMAPHORES */ + + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores_timed.cpp b/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores_timed.cpp new file mode 100644 index 0000000..fba9688 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/test/semaphores_timed.cpp @@ -0,0 +1,192 @@ +/** + * @file /src/test/semaphores_timed.cpp + * + * @brief Unit Test for timed semaphores. + * + * @date August, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/ipc/semaphore.hpp" +#include "../../include/ecl/ipc/shared_memory.hpp" + +#ifdef ECL_HAS_SEMAPHORES + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::SharedMemory; +using ecl::Semaphore; +using ecl::Duration; +using ecl::Sleep; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace ipc { +namespace tests { + +/***************************************************************************** +** Data Storage Class +*****************************************************************************/ + +class SemaphoreTimedData { + public: + double value[2]; + void initialise() { value[0] = 1.0; value[1] = 2.0; }; +}; + +} // namespace tests +} // namespace ipc +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::ipc::tests::SemaphoreTimedData; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @endcond + */ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SemaphoreTimedTests,access) { + + string sm_name("shared_memory"); + string sem_name("shared_semaphore"); + Sleep sleep; + Duration timeout(0,750000000); + + pid_t pID = fork(); + if (pID == 0) + { + /********************************************************************* + ** Child + *********************************************************************/ +// std::cout << "Child waiting" << std::endl; + sleep(1); + try { + SharedMemory sm(sm_name); + Semaphore semaphore(sem_name); +// std::cout << "Child trying the lock for 750ms" << std::endl; + bool result = semaphore.trylock(timeout); + EXPECT_FALSE(result); + if ( result ) { +// std::cout << "Child locked semaphore." << std::endl; + } else { +// std::cout << "Child lock attempt timed out." << std::endl; +// std::cout << "Child trying the lock again for 750ms" << std::endl; + if ( (result = semaphore.trylock(timeout)) ) { + EXPECT_TRUE(result); +// std::cout << "Child locked semaphore." << std::endl; + } else { +// std::cout << "Child lock attempt timed out." << std::endl; + } + } + semaphore.unlock(); + } catch ( ecl::StandardException &e ) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } + else if (pID < 0) // failed to fork + { + std::cerr << "Failed to fork" << std::endl; + exit(1); + } + else + { + /********************************************************************* + ** Parent + *********************************************************************/ + try { + SharedMemory sm(sm_name); + Semaphore semaphore(sem_name); + SemaphoreTimedData *data = sm.data(); + semaphore.lock(); + data->value[0] = 1.3; + data->value[1] = 2.3; + EXPECT_EQ(1.3,data->value[0]); + EXPECT_EQ(2.3,data->value[1]); +// std::cout << "Parent in the shared memory" << std::endl; +// std::cout << "Parent locking the semaphore." << std::endl; + sleep(2); +// std::cout << "Parent unlocking the semaphore." << std::endl; + semaphore.unlock(); + sleep(2); + } catch ( ecl::StandardException &e ) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << std::endl; + std::cout << "What you should see:" << std::endl; + std::cout << " - Process forks" << std::endl; + std::cout << " - Parent creates shared memory." << std::endl; + std::cout << " - Parent locks a semaphore and enters shared memory for 2 seconds." << std::endl; + std::cout << " - Child waits one second and tries lock for 750ms." << std::endl; + std::cout << " - Child fails and again tries lock for 750ms." << std::endl; + std::cout << " - Child succeeds in locking.." << std::endl; + std::cout << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +#else + +/***************************************************************************** +** Alternative Main +*****************************************************************************/ + +int main(int /* argc */, char ** /* argv */) { + std::cout << std::endl; + std::cout << "Semaphores are not supported on this platform (or ecl is just lacking)." << std::endl; + std::cout << std::endl; + return 0; +} + +#endif /* ECL_HAS_SEMAPHORES */ + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_ipc/src/test/shared_memory.cpp b/ros2_ws/src/ecl_core/ecl_ipc/src/test/shared_memory.cpp new file mode 100644 index 0000000..51343a3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_ipc/src/test/shared_memory.cpp @@ -0,0 +1,162 @@ +/** + * @file /src/test/shared_memory.cpp + * + * @brief Unit Test for the shared memory classes. + * + * @date August 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/ipc/shared_memory.hpp" + +#ifdef ECL_HAS_SHARED_MEMORY +// Should check for posix support too because we're using posix fork, but +// posix is all we got for now, so don't care too much. + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::cout; +using std::endl; +using std::cerr; +using std::string; +using ecl::SharedMemory; +using ecl::Sleep; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace ipc { +namespace tests { + +/***************************************************************************** +** Data Storage Class +*****************************************************************************/ + +class Data { + public: + Data(double d1 = 0.0, double d2 = 0.0) {value[0] = d1; value[1] = d2;} + double value[2]; +}; + +} // namespace tests +} // namespace ipc +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::ipc::tests::Data; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @endcond + */ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SharedMemoryTests,access) { + + string name("shared_memory"); + Sleep sleep; + + pid_t pID = fork(); + if (pID == 0) + { + /********************************************************************* + ** Child + *********************************************************************/ + sleep(1); + try { + SharedMemory sm(name.c_str()); + Data *data = sm.data(); + EXPECT_EQ(1.3,data->value[0]); + EXPECT_EQ(2.3,data->value[1]); +// cout << "Child read: " << data->value[0] << " " << data->value[1] << endl; + } catch ( ecl::StandardException &e) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } + else if (pID < 0) // failed to fork + { + cerr << "Failed to fork" << endl; + exit(1); + } + else + { + /********************************************************************* + ** Parent + *********************************************************************/ + try { + SharedMemory sm(name.c_str()); + Data *data = sm.data(); + data->value[0] = 1.3; + data->value[1] = 2.3; + EXPECT_EQ(1.3,data->value[0]); + EXPECT_EQ(2.3,data->value[1]); +// cout << "Parent wrote: " << data->value[0] << " " << data->value[1] << endl; + sleep(4); + } catch ( ecl::StandardException &e) { + // Don't fail the test, hudson doesn't let us have permissions for instance. + std::cout << e.what() << std::endl; + } + } +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +#else + +/***************************************************************************** +** Alternative Main +*****************************************************************************/ + +int main(int /* argc */, char ** /* argv */) { + std::cout << std::endl; + std::cout << "Shared memory is not supported on this platform (or ecl is just lacking)." << std::endl; + std::cout << std::endl; + return 0; +} + +#endif /* ECL_HAS_SHARED_MEMORY */ + + + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/.cproject b/ros2_ws/src/ecl_core/ecl_linear_algebra/.cproject new file mode 100644 index 0000000..1f03161 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/.cproject @@ -0,0 +1,650 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/.project b/ros2_ws/src/ecl_core/ecl_linear_algebra/.project new file mode 100644 index 0000000..f1f1ef1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/.project @@ -0,0 +1,78 @@ + + + ecl_linear_algebra + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_linear_algebra/CHANGELOG.rst new file mode 100644 index 0000000..c7eaf15 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/CHANGELOG.rst @@ -0,0 +1,19 @@ +========= +Changelog +========= + +0.61.8 (2016-01-10) +------------------- +* drop the c++11 transitive export flag, catkin installs dont support this + +0.61.7 (2016-01-09) +------------------- +* transitively export c++11 requirement instead of forcing users to do it + +0.61.5 (2015-11-24) +------------------- +* expose sophus and add some sophus helpers/utilities. + +0.61.0 (2014-09-12) +------------------- +* eigen matrix formatter api aligned with other ecl float formatters diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/CMakeLists.txt new file mode 100644 index 0000000..f0d5244 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/CMakeLists.txt @@ -0,0 +1,60 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_linear_algebra) + +############################################################################## +# ament +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_eigen REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_math REQUIRED) + +find_package(Sophus REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_eigen + ecl_exceptions + ecl_formatters + ecl_math + Sophus +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/cmake/FindEigen3.cmake b/ros2_ws/src/ecl_core/ecl_linear_algebra/cmake/FindEigen3.cmake new file mode 100644 index 0000000..9c546a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/cmake/FindEigen3.cmake @@ -0,0 +1,81 @@ +# - Try to find Eigen3 lib +# +# This module supports requiring a minimum version, e.g. you can do +# find_package(Eigen3 3.1.2) +# to require version 3.1.2 or newer of Eigen3. +# +# Once done this will define +# +# EIGEN3_FOUND - system has eigen lib with correct version +# EIGEN3_INCLUDE_DIR - the eigen include directory +# EIGEN3_VERSION - eigen version + +# Copyright (c) 2006, 2007 Montel Laurent, +# Copyright (c) 2008, 2009 Gael Guennebaud, +# Copyright (c) 2009 Benoit Jacob +# Redistribution and use is allowed according to the terms of the 2-clause BSD license. + +if(NOT Eigen3_FIND_VERSION) + if(NOT Eigen3_FIND_VERSION_MAJOR) + set(Eigen3_FIND_VERSION_MAJOR 2) + endif(NOT Eigen3_FIND_VERSION_MAJOR) + if(NOT Eigen3_FIND_VERSION_MINOR) + set(Eigen3_FIND_VERSION_MINOR 91) + endif(NOT Eigen3_FIND_VERSION_MINOR) + if(NOT Eigen3_FIND_VERSION_PATCH) + set(Eigen3_FIND_VERSION_PATCH 0) + endif(NOT Eigen3_FIND_VERSION_PATCH) + + set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") +endif(NOT Eigen3_FIND_VERSION) + +macro(_eigen3_check_version) + file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) + + string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}") + set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}") + set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}") + set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") + + set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) + if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + set(EIGEN3_VERSION_OK FALSE) + else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + set(EIGEN3_VERSION_OK TRUE) + endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + + if(NOT EIGEN3_VERSION_OK) + + message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " + "but at least version ${Eigen3_FIND_VERSION} is required") + endif(NOT EIGEN3_VERSION_OK) +endmacro(_eigen3_check_version) + +if (EIGEN3_INCLUDE_DIR) + + # in cache already + _eigen3_check_version() + set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) + +else (EIGEN3_INCLUDE_DIR) + + find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library + PATHS + ${CMAKE_INSTALL_PREFIX}/include + ${KDE4_INCLUDE_DIR} + PATH_SUFFIXES eigen3 eigen + ) + + if(EIGEN3_INCLUDE_DIR) + _eigen3_check_version() + endif(EIGEN3_INCLUDE_DIR) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) + + mark_as_advanced(EIGEN3_INCLUDE_DIR) + +endif(EIGEN3_INCLUDE_DIR) + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/mainpage.dox new file mode 100644 index 0000000..7906426 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/mainpage.dox @@ -0,0 +1,220 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Classes, representations and methods for manipulation of matrices. + + @subsection otherLibraries Other Libraries + + - BLAS : fast, but awkward c library, often used as the backend for other c++ libraries. + - BOOST : uses blas, main focus is c++ correctness and versatility of matrix types, not speed. + - BLITZ++ : containers only, uses template tricks, but almost discontinued. + - MKL : uses blas and focuses on multi-threading and multi-core performance specialised for intel chips. + - TVMET : optimised for low-order matrices through heavy use of template tricks. + + The c++ libraries are all hobbled in one way or another. Most can't deal with aliasing intelligently, + leaving it up to the user to handle that facet of matrix manipulation. They often use template + expressions also, which is great for speeding up operations, but matrix multiplication regularly + gets confused and bogged down - another thing that is left to the user to handle. + + Eigen is the new kid on the block and the one that + is used here. It handles aliasing and nested matrix multiplication without a problem, + includes important linear algebra modules (i.e. not just containers) and prioritises speed first, + then c++ conveniences (but still manages to be more convenient than ublas!). + +@section Prerequisites + + Using ros eigen now, but you can also opt to use the internal ecl_eigen. + +@section CompilingLinking Compiling & Linking + + @code + // If you want to use the internal eigen + // #define ECL_EIGEN_IS_INTERNAL + + // This brings in the whole library + #include + + // These calls bring in the individual modules + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + // There will also be some unsupported modules in ecl/linear_algebra/unsupported. + #include + #include + + // Aliasing the Eigen namespace (for convenience) + using namespace ecl::linear_algebra + @endcode + + Note that the namespace is simply an alias to the Eigen namespace. You can use either + namespace, however the ecl namespace is preferred so its clear we're using our + extended interface (via the eigen plugins). + + Since eigen is a template class, no linking is required if you are only using eigen's classes. + +@section usage Usage + +@subsection Eigen + + The following are some important links for us back to the eigen documentation: + + - Documentation Frontend + - Lazy Evaluation + - Writing Optimised Expressions + - Decompositions Overview + - Modifications needed for Classes with Eigen Members + - Stl containers and eigen + + Some important points to note (more detailed notes regarding some eigen specific issues further below): + + - Matrices/Vectors of all types are built from the one base class. + - Typedefs exist for all common forms of matrices and vectors (important for vectors as there is no Vector class). + + The ecl supplements the eigen library with a few extras features. + +@subsection eigenPlugin Eigen Plugin + + The eigen matrixbase class provides a way to extend its api via a macro-based plugin. The trick is enabled + by the following code in eigen's MatrixBase class: + + @code + class MatrixBase { + // ... + #ifdef EIGEN_MATRIXBASE_PLUGIN + #include EIGEN_MATRIXBASE_PLUGIN + #endif + }; + @endcode + + Here we take advantage of it to add the following api: + + - conservativeResize(int rows, int cols) : matrix resizing, carrying over existing elements + - conservativeResize(int rows) : vector resizing, carrying over existing elements + + This will be brought in if you do one of the following before you include any eigen + headers: + + @code + #define EIGEN_MATRIXBASE_PLUGIN + // OR the ecl bundle + #include + // OR any one of the ecl-eigen3 modules + #include + @endcode + + Note that if you wish to customise the eigen plugin differently, simply define the macro, + pointing it at your own customisation before including ecl/linear_algebra.hpp. The ecl plugin + makes a check and won't override any existing definitions. + +@subsection Alignment + + You have to be very careful with eigen to make sure alignment works properly. This is a bit + of a pain in the bum, but will result in hardware speedups. If you see the following error + message + + @code + /opt/ros/ecl/ecl_core/ecl_linear_algebra/include/ecl/Eigen2/src/Core/MatrixStorage.h:44: + Eigen::ei_matrix_array::ei_matrix_array() [with T = double, + int Size = 4, int MatrixOptions = 2, bool Align = true]: Assertion + `(reinterpret_cast(array) & 0xf) == 0 && "this assertion is explained here: + http://eigen.tuxfamily.org/dox/UnalignedArrayAssert.html **** READ THIS WEB PAGE !!! ****"' + failed. + @endcode + + its probably because you need to fix your storage mechanism for classes with eigen + vectors inside them. See that web page for more detail and/or run gdb on your program to see + where the compile time assert triggered. + + Usual scenario - you have used an eigen type of fixed size as a storage container + embeddded inside a class or struct, or inherited a class that does so. + + - only for fixed size eigen types + - fixed size eigen type is inside the class or inside an inherited class + + In this situation, you need to add the following macro to the public section + of the class as well as each class that inherits this class. + + @code + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + @endcode + +@subsection stdVector Std Vector + + If always calling linear_algebra.hpp to access eigen, it will bring in Eigen's NewStdVector + implementation. This will use it for eigen types and default to the original std vector for + other types, but there's one caveat. For eigen to distinguish, you need to specify the + vector allocator. + + @code + #include + + int main(int argc, char **argv) { + + std::vector< Eigen::Vector2d, Eigen::aligned_allocator > vv; // eigen's std vector implementation + std::vector vd; // std's vector implementation + + Eigen::Vector2d v; v << 1,2; + vv.push_back(v); vv.push_back(v); + std::cout << vv[0] << std::endl; + + return 0; + } + + @endcode + + If you do not include it, you will see the usual compile time alignment warning that Eigen loves. + +@subsection Formatters + + Formatters have been included in the plugin for float and double type matrices + (may expand to integral types later if we need them). This is achieved by use of the ecl_formatters + framework. + + There are several ways you can call these formatters, the most convenient methods are outlined below: + + @code + #include + Matrix2d m; m << 1.0, 2.0, 3.0, 4.0; + Matrix2d::Formatter formatter(3,6); // prec 3, width 6 + formatter.precision(2); formatter.width(5); + std::cout << formatter(m) << std::cout; // format using the stored settings + std::cout << formatter(m,3,6) << std::cout; // format using one-shot settings + @endcode + + @code + #include + #include + Matrix2d m; m << 1.0, 2.0, 3.0, 4.0; + Format format(3,6); // prec 3, width 6 + format.precision(2); format.width(5); + std::cout << format(m) << std::cout; // format using the stored settings + std::cout << format(m,3,6) << std::cout; // format using one-shot settings + @endcode + +\section ChangeLog + + - Mar 12 : depracated Eigen3. + - Dec 10 : switched the default to eigen3, also brought in unsupported modules for numerical differentiation and nonlinear optimisation. + - Sep 10 : added a formatter for float type matrices with precision and width control. + - Aug 10 : incorporated the new std vector implementation explicitly in linear_algebra.hpp. + - Jul 10 : embedded the eigen3 library in the ecl. + - May 10 : embedded the eigen2 library in the ecl. + - Oct 09 : conservative resizing functions added to the eigen plugin. + - May 09 : namespace alias to eigen set up. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/namespaces.dox new file mode 100644 index 0000000..b1fda5c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/doxygen/namespaces.dox @@ -0,0 +1,7 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..1567c03 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(linear_algebra) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra.hpp new file mode 100644 index 0000000..432a5e3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra.hpp @@ -0,0 +1,32 @@ +/** + * @file /include/ecl/linear_algebra.hpp + * + * @brief Mathematical tools for linear algebra. + * + * Various linear algebraic classes and methods aliased to and provided + * by the eigen library. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_LINEAR_ALGEBRA_HPP_ +#define ECL_LINEAR_ALGEBRA_HPP_ + +#ifdef _MSC_VER +#define _USE_MATH_DEFINES +#include // M_PI +#endif // _MSC_VER + +#include "linear_algebra/eigen.hpp" +#include "linear_algebra/sophus.hpp" + +// want to get rid of this, but there is legacy issues. +namespace ecl { + namespace linear_algebra = Eigen; +} + +#endif /*ECL_MATH_LINEAR_ALGEBRA_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/.gitignore b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/.gitignore new file mode 100644 index 0000000..674d8b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/.gitignore @@ -0,0 +1 @@ +macros.hpp diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/CMakeLists.txt new file mode 100644 index 0000000..53a1c62 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/CMakeLists.txt @@ -0,0 +1,15 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(eigen) +add_subdirectory(sophus) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/linear_algebra) + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen.hpp new file mode 100644 index 0000000..ce583a6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen.hpp @@ -0,0 +1,39 @@ +/** + * @file /ecl_linear_algebra/include/ecl/linear_algebra/eigen.hpp + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_linear_algebra_LINEAR_ALGEBRA_EIGEN_HPP_ +#define ecl_linear_algebra_LINEAR_ALGEBRA_EIGEN_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "eigen/formatters.hpp" + +#ifndef EIGEN_MATRIXBASE_PLUGIN + #define EIGEN_MATRIXBASE_PLUGIN +#endif + +#include +#include +#include +#include +#include +#include +#include +// #include // This is an eigen2 support module, forget it. +#include +#include +// This one is bad - it doesn't inline its headers (Eigen v3.01) - avoid it for now. +// #include +#include +#include +#include +#include +#include + +#endif /* ecl_linear_algebra_LINEAR_ALGEBRA_EIGEN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/CMakeLists.txt new file mode 100644 index 0000000..3db0024 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(unsupported) + +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/linear_algebra/eigen) diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/formatters.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/formatters.hpp new file mode 100644 index 0000000..5040c7b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/formatters.hpp @@ -0,0 +1,258 @@ +/** + * @file /ecl_linear_algebra/include/ecl/linear_algebra/formatters.hpp + * + * @brief Formatters for eigen types. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_LINEAR_ALGEBRA_FORMATTERS_HPP_ +#define ECL_LINEAR_ALGEBRA_FORMATTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace Eigen { + +/***************************************************************************** +** Interface [MatrixFormatter] +*****************************************************************************/ + +/** + * @brief Parent for matrix formatters - used to negate unimplemented formatters. + * + * This is not to be used directly, rather the specialisations will implement + * the matrix formatter. + */ +template +class MatrixFormatter { +private: + MatrixFormatter() {} +}; + +/***************************************************************************** +** Interface [FloatMatrixFormatter] +*****************************************************************************/ + +/** + * @brief Formatter for Eigen matrix type + * + * I want make it formatting any types of eigen + * + * @tparam Derived : MatrixBase's type which specify the matrix as vector, matrix with any storage type + * + * @todo + * specialise the formatting; now it just support the float type only. + */ +template +class FloatMatrixFormatter { +public: + /****************************************** + ** C&D's + *******************************************/ + /** + * @brief Default constructor. + * + * Initialises the format tags for width, and precision. + * @param w : width (default - no width constraints) + * @param p : the number of decimal places of precision (default - 4) + **/ + FloatMatrixFormatter(const int &w = -1, const unsigned int &p = 2) : + tmp_formatting(false), + ready_to_format(false), + _matrix(NULL) + { + format.width(w); + format.precision(p); + } + virtual ~FloatMatrixFormatter() {} + + /****************************************** + ** Configuration + *******************************************/ + /** + * @brief Sets the precision format parameter. + * + * Sets the precision format parameter. + * + * @param p : the number of decimal places of precision. + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + FloatMatrixFormatter& precision( const unsigned int &p ) { + format.precision(p); + return *this; + } + + /** + * @brief Sets the width format parameter. + * + * Sets the width format parameter. + * + * @param w : the width to use for inserted floats (-1 is no width constraint). + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + FloatMatrixFormatter& width( const int &w ) { + format.width(w); + return *this; + } + + /** + * @brief Returns the current precision setting. + * @return unsigned int : the precision value. + */ + unsigned int precision() { return format.precision(); } + + /** + * @brief Returns the current width setting. + * @return int : the witdh value (-1 for no width constraint). + */ + int width() { return format.width(); } + + /****************************************** + ** Format a value + *******************************************/ + /** + * @brief Format a matrix with permanently stored precision/width. + * + * This function directly formats the specified input value + * with the stored settings. + * @code + * Vector2d v; v << 1.0, 2.0; + * Format format; + * cout << format(v) << endl; + * @endcode + * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer). + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + FloatMatrixFormatter< Derived >& operator() (const Derived & matrix ) { + _matrix = &matrix; + ready_to_format = true; + return (*this); + } + /** + * @brief Format a matrix with temporarily specified precision/width. + * + * This function directly formats the specified input value + * and temporary settings. + * + * @code + * Vector2d v; v << 1.0, 2.0; + * Format format; + * cout << format(v,3,-1) << endl; // precision of 3 and no width constraint + * @endcode + * + * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer). + * @param w : the width to use for inserted floats (-1 is no width constraint). + * @param p : the number of decimal places of precision. + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + FloatMatrixFormatter< Derived >& operator() (const Derived & matrix, const int &w, const unsigned int &p) { + _matrix = &matrix; + tmp_precision = p; + tmp_width = w; + tmp_formatting = true; + ready_to_format = true; + return (*this); + } + + /** + * @brief Stream the formatter. + * + * Insertion operator for sending the formatter to an output stream. + * + * @param ostream : the output stream. + * @param formatter : the formatter to be inserted. + * @tparam OutputStream : the type of the output stream to be inserted into. + * @tparam Derived : matrix type. + * @return OutputStream : continue streaming with the updated output stream. + * + * @exception StandardException : throws if the formatter has un-specified _matrix [debug mode only] + */ + template + friend OutputStream& operator << ( OutputStream& ostream, FloatMatrixFormatter & formatter ); + + private: + ecl::Format format; + int tmp_width; + unsigned int tmp_precision; + bool tmp_formatting; + bool ready_to_format; + const Derived *_matrix; +}; + +template +OutputStream& operator << (OutputStream& ostream, FloatMatrixFormatter< Derived_ > & formatter ) +{ + ecl_assert_throw( formatter._matrix, ecl::StandardException(LOC,ecl::UsageError,"The formatter cannot print any data - " + "_matrix was not initialised " + "please pass the your matrix through () operator") ); + ecl_assert_throw(formatter.ready_to_format, ecl::StandardException(LOC,ecl::UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + + if ( formatter.ready_to_format ) { + unsigned int prm_precision = formatter.format.precision();; + int prm_width = formatter.format.width(); + if ( formatter.tmp_formatting ) { + formatter.format.precision(formatter.tmp_precision); + formatter.format.width(formatter.tmp_width); + } + + /********************* + ** Stream Matrix + **********************/ + // write matrix data + // @note norma matrix allows matrix(i,j) however sparse matrix does not. + // So i put coeff(i,j) function which can be used for accessing each element for both of sparse and dense. + int rows = formatter._matrix->rows(); + int cols = formatter._matrix->cols(); + for( int i=0; icoeff( i, j )) << " "; + } + if ( rows != 1 ) { // special condition for row vectors so we can do inline the formatting. + ostream << "\n"; + } + } + + if ( formatter.tmp_formatting ) { + formatter.format.precision(prm_precision); + formatter.format.width(prm_width); + formatter.tmp_formatting = false; + } + formatter.ready_to_format = false; + } + return ostream; +} + +/***************************************************************************** +** Interface [MatrixFormatter][Float Types] +*****************************************************************************/ + +template +class MatrixFormatter >::type> : public FloatMatrixFormatter { +public: + MatrixFormatter(const int &w = -1, const unsigned int &p = 2) : FloatMatrixFormatter(w, p) {}; +}; + +} // namespace Eigen + +#endif /* ECL_LINEAR_ALGEBRA_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/plugin.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/plugin.hpp new file mode 100644 index 0000000..1a139b0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/plugin.hpp @@ -0,0 +1,59 @@ +/** + * @file /include/ecl/linear_algebra/eigen_plugin.hpp + * + * @brief Customises the eigen matrixbase class via the plugin handle. + * + * Populates the eigen matrix base class with a few extra functions via + * the EIGEN_MATRIXBASE_PLUGIN macro. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_LINEAR_ALGEBRA_EIGEN_PLUGIN_HPP_ +#define ECL_LINEAR_ALGEBRA_EIGEN_PLUGIN_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "formatters.hpp" + +/***************************************************************************** +** Code +*****************************************************************************/ + +typedef MatrixFormatter Formatter; + +inline void conservativeResize(int rows, int cols) +{ + PlainObject tmp(rows, cols); // alternatively: PlainObject::Zero(rows,cols) + const int common_rows = std::min(rows, this->rows()); + const int common_cols = std::min(cols, this->cols()); + tmp.block(0,0,common_rows,common_cols) = this->block(0,0,common_rows,common_cols); + this->derived().swap(tmp); +} + +inline void conservativeResize(int size) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + + if (RowsAtCompileTime == 1) + { + PlainObject tmp(1,size); // alternatively: PlainObject::Zero(1,size) + const int common_size = std::min(cols(),size); + tmp.block(0,0,1,common_size) = this->block(0,0,1,common_size); + this->derived().swap(tmp); + } + else + { + PlainObject tmp(size,1); // alternatively: PlainObject::Zero(size,1) + const int common_size = std::min(rows(),size); + tmp.block(0,0,common_size,1) = this->block(0,0,common_size,1); + this->derived().swap(tmp); + } +} + +#endif /* ECL_LINEAR_ALGEBRA_EIGEN_PLUGIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/CMakeLists.txt new file mode 100644 index 0000000..7e09df5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/linear_algebra/eigen/unsupported) + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/nonlinear_optimization.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/nonlinear_optimization.hpp new file mode 100644 index 0000000..de70284 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/nonlinear_optimization.hpp @@ -0,0 +1,25 @@ +/** + * @file /ecl_linear_algebra/include/ecl/linear_algebra/unsupported/nonlinear_optimization.hpp + * + * @brief Unsupported nonlinear optimisation module. + * + * @date Dec 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_LINEAR_ALGEBRA_NONLINEAR_OPTIMIZATION_HPP_ +#define ECL_LINEAR_ALGEBRA_NONLINEAR_OPTIMIZATION_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#ifndef EIGEN_MATRIXBASE_PLUGIN +// #define EIGEN_MATRIXBASE_PLUGIN +#endif + +#include + +#endif /* ECL_LINEAR_ALGEBRA_NONLINEAR_OPTIMIZATION_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/numerical_diff.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/numerical_diff.hpp new file mode 100644 index 0000000..7d79503 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/eigen/unsupported/numerical_diff.hpp @@ -0,0 +1,25 @@ +/** + * @file /ecl_linear_algebra/include/ecl/linear_algebra/unsupported/numerical_diff.hpp + * + * @brief Unsupported numerical differentiation module. + * + * @date Dec 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_LINEAR_ALGEBRA_NUMERICAL_DIFF_HPP_ +#define ECL_LINEAR_ALGEBRA_NUMERICAL_DIFF_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#ifndef EIGEN_MATRIXBASE_PLUGIN + #define EIGEN_MATRIXBASE_PLUGIN +#endif + +#include + +#endif /* ECL_LINEAR_ALGEBRA_NUMERICAL_DIFF_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus.hpp new file mode 100644 index 0000000..3e6e66b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus.hpp @@ -0,0 +1,24 @@ +/** + * @file /ecl_linear_algebra/include/ecl/linear_algebra/sophus.hpp + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_linear_algebra_LINEAR_ALGEBRA_SOPHUS_HPP_ +#define ecl_linear_algebra_LINEAR_ALGEBRA_SOPHUS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +#include "sophus/helpers.hpp" +#include "sophus/formatters.hpp" +#include "sophus/interpolators.hpp" + +#endif /* ecl_linear_algebra_LINEAR_ALGEBRA_SOPHUS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/CMakeLists.txt new file mode 100644 index 0000000..60f7a2d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/linear_algebra/sophus) diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/formatters.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/formatters.hpp new file mode 100644 index 0000000..0e7f346 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/formatters.hpp @@ -0,0 +1,219 @@ +/** + * @file /ecl_linear_algebra/include/ecl_linear_algebra/sophus_formatters.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_linear_algebra_SOPHUS_FORMATTERS_HPP_ +#define ecl_linear_algebra_SOPHUS_FORMATTERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace Sophus { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +/** + * Formats the se3 in easily readable translation/quaternion syntax. + * + * If you are working with frames, what you usually want to read is the + * pose of the frame, i.e. the inverse of the transform. + * + * e.g. if you have T_cam_rel_map, to get the pose of the cam frame relative + * to the map frame, pass T_cam_rel_map.inverse() to this formatter. + */ +class SE3fFormatter +{ +public: + /** + * @brief Default constructor. + * + * Initialises the format tags for width, and precision. + * @param w : width (default - no width constraints) + * @param p : the number of decimal places of precision (default - 4) + **/ + SE3fFormatter(const int &w = -1, const unsigned int &p = 2) + : format(w, p, ecl::RightAlign) + , tmp_width(w) + , tmp_precision(p) + , tmp_formatting(false) + , ready_to_format(false) + , s_(NULL) +{} + virtual ~SE3fFormatter() {} + /** + * @brief Sets the precision format parameter. + * + * @param p : the number of decimal places of precision. + * @return SE3fFormatter& : this formatter readied for use with a stream. + **/ + SE3fFormatter& precision( const unsigned int &p ) { + format.precision(p); + return *this; + } + /** + * @brief Sets the width format parameter. + * + * Sets the width format parameter. + * + * @param w : the width to use for inserted floats (-1 is no width constraint). + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + SE3fFormatter& width( const int &w ) { + format.width(w); + return *this; + } + /** + * @brief Returns the current precision setting. + * @return unsigned int : the precision value. + */ + unsigned int precision() { return format.precision(); } + + /** + * @brief Returns the current width setting. + * @return int : the witdh value (-1 for no width constraint). + */ + int width() { return format.width(); } + + /** + * @brief Format a sophus transform with permanently stored precision/width. + * + * This function directly formats the specified input value + * with the stored settings. + * @code + * cout << format(Sophus::SE3f()) << endl; + * @endcode + * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer). + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + SE3fFormatter& operator() (const Sophus::SE3f & s ) { + s_ = &s; + ready_to_format = true; + return (*this); + } + /** + * @brief Format a matrix with temporarily specified precision/width. + * + * This function directly formats the specified input value + * and temporary settings. + * + * @code + * Sophus::SE3f s; + * cout << format(s,3,-1) << endl; // precision of 3 and no width constraint + * @endcode + * + * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer). + * @param w : the width to use for inserted floats (-1 is no width constraint). + * @param p : the number of decimal places of precision. + * @return FloatMatrixFormatter& : this formatter readied for use with a stream. + **/ + SE3fFormatter& operator() (const Sophus::SE3f & s, const int &w, const unsigned int &p) { + s_ = &s; + tmp_precision = p; + tmp_width = w; + tmp_formatting = true; + ready_to_format = true; + return (*this); + } + /** + * @brief Stream the formatter. + * + * Insertion operator for sending the formatter to an output stream. + * + * @param ostream : the output stream. + * @param formatter : the formatter to be inserted. + * @tparam OutputStream : the type of the output stream to be inserted into. + * @tparam Derived : matrix type. + * @return OutputStream : continue streaming with the updated output stream. + * + * @exception StandardException : throws if the formatter has un-specified _matrix [debug mode only] + */ + template + friend OutputStream& operator << ( OutputStream& ostream, SE3fFormatter & formatter ); + +private: + ecl::Format format; + int tmp_width; + unsigned int tmp_precision; + bool tmp_formatting; + bool ready_to_format; + const Sophus::SE3f *s_; +}; + +template +OutputStream& operator << (OutputStream& ostream, SE3fFormatter & formatter ) { + + ecl_assert_throw( formatter.s_, ecl::StandardException(LOC,ecl::UsageError,"The formatter cannot print any data - " + "sophus object was not initialised " + "please pass the your matrix through () operator") ); + + ecl_assert_throw(formatter.ready_to_format, ecl::StandardException(LOC,ecl::UsageError,"The formatter cannot print any data - " + "either there is no data available, or you have tried to use the " + "formatter more than once in a single streaming operation. " + "C++ produces unspecified results when functors are used multiply " + "in the same stream sequence, so this is not permitted here.") ); + + if ( formatter.ready_to_format ) { + unsigned int prm_precision = formatter.format.precision();; + int prm_width = formatter.format.width(); + if ( formatter.tmp_formatting ) { + formatter.format.precision(formatter.tmp_precision); + formatter.format.width(formatter.tmp_width); + } + + /********************* + ** Stream Sophus + **********************/ + Eigen::Vector3f translation = formatter.s_->translation(); + Eigen::Quaternionf quaternion = formatter.s_->unit_quaternion(); + ostream << "["; + ostream << "x:" << formatter.format(translation.x()) << " "; + ostream << "y:" << formatter.format(translation.y()) << " "; + ostream << "z:" << formatter.format(translation.z()); + ostream << "]"; + ostream << "["; + ostream << "x:" << formatter.format(quaternion.x()) << " "; + ostream << "y:" << formatter.format(quaternion.y()) << " "; + ostream << "z:" << formatter.format(quaternion.z()) << " "; + ostream << "w:" << formatter.format(quaternion.w()) << " "; + ostream << "]"; + + if ( formatter.tmp_formatting ) { + formatter.format.precision(prm_precision); + formatter.format.width(prm_width); + formatter.tmp_formatting = false; + } + formatter.ready_to_format = false; + } + return ostream; +} + +} // namespace Sophus + +/***************************************************************************** + ** ECL Format Type + *****************************************************************************/ + +namespace ecl { + + template <> + class Format : public Sophus::SE3fFormatter {}; + +} // namespace ecl + +#endif /* ecl_linear_algebra_SOPHUS_FORMATTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp new file mode 100644 index 0000000..41fb1cd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp @@ -0,0 +1,143 @@ +/** + * @file /yocs_math_toolkit/include/yocs_math_toolkit/sophus_helpers.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef yocs_math_toolkit_SOPHUS_HELPERS_HPP_ +#define yocs_math_toolkit_SOPHUS_HELPERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#if defined(ECL_CXX11_FOUND) + #include +#endif +#include +#include +#include +#include +#include + +#include "formatters.hpp" + +/***************************************************************************** +** Namespace +*****************************************************************************/ + +namespace Sophus { + +/***************************************************************************** + ** C++11 Api Only + *****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + typedef std::shared_ptr SE3fPtr; + + /// Converts a line drawn between two points on the z-plane into the transform of a sophus frame relative to the origin. + Sophus::SE3fPtr points2DToSophusTransform(float from_x, float from_y, float to_x, float to_y); +#endif + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +template +std::ostream & operator << ( std::ostream & out, const SE3 & se3 ) +{ +// typename SE3::Tangent tanget_vector = SE3::log( se3 ); +// out << tanget_vector.transpose(); + const Eigen::Matrix & t = se3.translation(); + const Eigen::Quaternion & q = se3.unit_quaternion(); + out << t.transpose() << " " << q.x() << " " << q.y() << " " << q.z() << " " << q.w(); + return out; +} + +template +std::ostream & operator << ( std::ostream & out, const SE2 & se2 ) +{ + typename SE2::Tangent tanget_vector = SE2::log( se2 ); + out << tanget_vector.transpose(); + return out; +} + +/** + * @brief Convert a full Sophus pose into a 2 dimensional pose. + * + * The 2d pose is a typical mobile robot 2d pose with (x, y, heading) with + * heading measured in radians. + **/ +Eigen::Vector3f toPose2D(const Sophus::SE3f& pose); +/** + * @brief Convert a 2 dimensional pose to a full Sophus pose in 3d. + * + * The 2d pose is a typical mobile robot 2d pose with (x, y, heading) with + * heading measured in radians. + **/ +Sophus::SE3f toPose3D(const Eigen::Vector3f& pose); + +class PlanarRotation2Quaternion +{ +public: + PlanarRotation2Quaternion(){} + Eigen::Quaternionf operator() ( float theta ) + { + Eigen::Matrix3f R = ( Eigen::AngleAxis (static_cast ( theta ), Eigen::Vector3f::UnitZ ()) ).matrix(); + Eigen::Quaternionf q(R); + q.normalize(); + return q; +// Eigen::Quaternionf q; +// // in this case x and y part is zero since we assumbed that rotationa round z axis on the xy-plane +// q.vec() << 0, 0, sin(theta*0.5f); +// q.w() = cos(theta*0.5f); +// q.normalize(); +// return q; + } + + void convert( float theta, Eigen::Quaternionf & q ) + { + q.vec() << 0, 0, sin(theta*0.5f); + q.w() = cos(theta*0.5f); + } +}; + + +} // namespace Sophus + +/***************************************************************************** +** Converters +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Converter class representing the Sophus::toPose3D method. + */ +template<> +class Converter { +public: + Sophus::SE3f operator()(const Eigen::Vector3f& pose); +}; + +/** + * @brief Converter class representing the Sophus::toPose2D method. + */ +template<> +class Converter { +public: + Eigen::Vector3f operator()(const Sophus::SE3f& pose); +}; + +} // namespace ecl + + +#endif /* yocs_math_toolkit_SOPHUS_HELPERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/interpolators.hpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/interpolators.hpp new file mode 100644 index 0000000..52c5504 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/interpolators.hpp @@ -0,0 +1,110 @@ +/** + * @file include/ecl/sophus/interpolators.hpp + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef yocs_math_toolkit_SOPHUS_INTERPOLATERS_HPP_ +#define yocs_math_toolkit_SOPHUS_INTERPOLATERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formatters.hpp" + +/***************************************************************************** +** Namespace +*****************************************************************************/ + +namespace Sophus { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + + +/** + * @brief Interpolate between two lie group objects. + * + * Working with Sophus::SE3f classes, but haven't tested with the other + * group types yet. + * + * Refer to Section 7 in http://ethaneade.com/lie.pdf. + * + * An alternative (slow/fast?) way of returning the result is: + * + * @code + * Group::exp(t*tangent_a + (1.0-t)*tangent_b); + * @endcode + */ +template +class Interpolator { +public: + Interpolator(const Group& T_a, const Group& T_b) + : T_a(T_a) + { + Group T_b_rel_a = T_b*T_a.inverse(); + tangent = T_b_rel_a.log(); + } + Group operator()(const double& t) { + return Group::exp(t*tangent)*T_a; + } +private: + Group T_a; + typename Group::Tangent tangent; +}; + +/** + * A special case of the interpolator that takes two coplanar frames and + * interpolates between them. + * + * The plane is defined by the first frame and the T_b_rel_a must be able + * to be represented by a SE2 transformation (no z-translation and yaw rotation only). + * + * This is oft used when dealing with SE3 frames fixed on the z plane. + */ +class PlanarInterpolator { +public: + PlanarInterpolator(const Sophus::SE3f& T_a, const Sophus::SE3f& T_b); + Sophus::SE3f operator()(const double& t); + +private: + Sophus::SE3f T_a; + Sophus::SE2f t_a; + Sophus::SE2f::Tangent tangent; +}; + +/** + * A special case of the interpolator that slides along the straight line + * connecting two frames whilst interpolating the orientation between the two. + * + * Normal se3 interpolation will not guarantee a straight line connection + * if there is a rotation involved. i.e. it will swing its hips like it is + * dancing! + */ +class SlidingInterpolator { +public: + SlidingInterpolator(const Sophus::SE3f& T_a, const Sophus::SE3f& T_b); + Sophus::SE3f operator()(const double& t); + +private: + Interpolator interpolator; + Sophus::SE3f T_a, T_b; + Sophus::SE3f::Tangent tangent; +}; + + +} // namespace Sophus + +#endif /* yocs_math_toolkit_SOPHUS_INTERPOLATERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/package.xml b/ros2_ws/src/ecl_core/ecl_linear_algebra/package.xml new file mode 100644 index 0000000..05309a2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/package.xml @@ -0,0 +1,44 @@ + + + ecl_linear_algebra + 1.2.1 + + Ecl frontend to a linear matrix package (currently eigen). + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_linear_algebra + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_build + ecl_converters + ecl_eigen + ecl_exceptions + ecl_formatters + ecl_license + ecl_math + sophus + + ecl_build + ecl_converters + ecl_eigen + ecl_exceptions + ecl_formatters + ecl_license + ecl_math + sophus + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/rosdoc.yaml b/ros2_ws/src/ecl_core/ecl_linear_algebra/rosdoc.yaml new file mode 100644 index 0000000..239fcd1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/rosdoc.yaml @@ -0,0 +1,2 @@ + - builder: doxygen + file_patterns: '*.hpp *.dox' diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/CMakeLists.txt new file mode 100644 index 0000000..45123f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/CMakeLists.txt new file mode 100644 index 0000000..86bbd2c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/CMakeLists.txt @@ -0,0 +1,45 @@ +############################################################################## +# Sources +############################################################################## + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################## +# Library +############################################################################## + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + PUBLIC + "$" + "$" +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_eigen::ecl_eigen + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_math::ecl_math + Sophus::Sophus +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +############################################################################## +# Installs +############################################################################## + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_helpers.cpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_helpers.cpp new file mode 100644 index 0000000..b6388a6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_helpers.cpp @@ -0,0 +1,78 @@ +/** + * @file /ecl_linear_algebra/src/lib/sophus_helpers.cpp + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/linear_algebra/sophus/helpers.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace Sophus { + +/***************************************************************************** +** Vanilla Implementation +*****************************************************************************/ + +Eigen::Vector3f toPose2D(const Sophus::SE3f& pose) +{ + Eigen::Vector3f pose2d; + + Eigen::Matrix3f R = pose.rotationMatrix(); + float yaw_angle = std::atan2( R(1,0), R(0,0) ); + pose2d.head<2>() = pose.translation().head<2>(); + pose2d.z() = yaw_angle; + return pose2d; +} + +Sophus::SE3f toPose3D(const Eigen::Vector3f& pose) +{ + Eigen::Matrix3f rotation_matrix = ( + Eigen::AngleAxis (pose(2), Eigen::Vector3f::UnitZ ()) * + Eigen::AngleAxis (0.0f, Eigen::Vector3f::UnitY ()) * + Eigen::AngleAxis (0.0f, Eigen::Vector3f::UnitX ()) ).matrix(); + Eigen::Vector3f translation; + translation << pose.x(), pose.y(), 0.0f; + Sophus::SE3f pose3d(rotation_matrix, translation); + + return pose3d; +} + +/***************************************************************************** +** C++11 Implementation +*****************************************************************************/ + +#if defined(ECL_CXX11_FOUND) + Sophus::SE3fPtr points2DToSophusTransform(float from_x, float from_y, float to_x, float to_y) { + // copied code from output receiver + Eigen::Vector3f origin(from_x, from_y, 0.0); + double angle = std::atan2(to_y-from_y, to_x-from_x); + Eigen::Quaternion q; q = Eigen::AngleAxis(angle, Eigen::Vector3f::UnitZ()); + return std::make_shared(q, origin); + // std::cout << " Origin: " << origin.transpose() << std::endl; + // std::cout << " Angle : " << angle << std::endl; + } +#endif + +} // namespace Sophus + +/***************************************************************************** +** Converters +*****************************************************************************/ + +namespace ecl { + +Sophus::SE3f Converter::operator()(const Eigen::Vector3f& pose) { + return Sophus::toPose3D(pose); +} + +Eigen::Vector3f Converter::operator()(const Sophus::SE3f& pose) { + return Sophus::toPose2D(pose); +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_interpolators.cpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_interpolators.cpp new file mode 100644 index 0000000..21b83f2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/lib/sophus_interpolators.cpp @@ -0,0 +1,66 @@ +/** + * @file /ecl_linear_algebra/src/sophus_interpolators.cpp + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/linear_algebra/sophus/interpolators.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace Sophus { + +/***************************************************************************** +** Planar Interpolator +*****************************************************************************/ + +PlanarInterpolator::PlanarInterpolator(const Sophus::SE3f& T_a, const Sophus::SE3f& T_b) +: T_a(T_a) +{ + double epsilon = 0.00001; + Sophus::SE3f T_b_rel_a = T_b*T_a.inverse(); + Sophus::SE3f pose_b_rel_a = T_b_rel_a.inverse(); + Eigen::Vector3f translation = pose_b_rel_a.translation(); + ecl_assert_throw( std::abs(translation.z()) < epsilon, ecl::StandardException(LOC, ecl::InvalidArgError, "Input transforms are not coplanar.")); + + // TODO check the angle axis is the z-axis + + float axis_angle = T_b_rel_a.inverse().so3().log()(2); + Sophus::SE2f t_b_rel_a = Sophus::SE2f(axis_angle, translation.head<2>()).inverse(); + tangent = t_b_rel_a.log(); + (void) epsilon; // for unused variable warnings, in case the assert wasn't triggered +} +Sophus::SE3f PlanarInterpolator::operator()(const double& t) { + Sophus::SE2f t_t_rel_a = Sophus::SE2f::exp(t*tangent); + float angle = t_t_rel_a.inverse().so2().log(); + Eigen::Vector3f translation; + translation.head<2>() = t_t_rel_a.inverse().translation(); + translation(2) = 0.0; + Eigen::Matrix3f R = Eigen::AngleAxis (angle, Eigen::Vector3f::UnitZ ()).matrix(); + Sophus::SE3f T_t_rel_a = Sophus::SE3f(R, translation).inverse(); + return T_t_rel_a*T_a; +} + +/***************************************************************************** +** Sliding Interpolator +*****************************************************************************/ + +SlidingInterpolator::SlidingInterpolator(const Sophus::SE3f& T_a, const Sophus::SE3f& T_b) +: interpolator(T_a, T_b), T_a(T_a), T_b(T_b) +{ +} + +Sophus::SE3f SlidingInterpolator::operator()(const double& t) { + Eigen::Vector3f translation_a = T_a.inverse().translation(); + Eigen::Vector3f translation_b = T_b.inverse().translation(); + Eigen::Vector3f translation = translation_a + t*(translation_b - translation_a); + Sophus::SE3f T_t_rel_a = interpolator(t); + return Sophus::SE3f(T_t_rel_a.inverse().unit_quaternion(), translation).inverse(); +} + + +} // namespace Sophus diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/CMakeLists.txt new file mode 100644 index 0000000..90ef05b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/CMakeLists.txt @@ -0,0 +1,36 @@ +############################################################################## +# Google Test Macro +############################################################################## + +macro(ecl_linear_algebra_add_gtest test_name) + ament_add_gtest(ecl_test_linear_algebra_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_linear_algebra_${test_name}) + target_include_directories( + ecl_test_linear_algebra_${test_name} + PRIVATE + $ + ) + target_link_libraries(ecl_test_linear_algebra_${test_name} + ${PROJECT_NAME} + ecl_eigen::ecl_eigen + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_math::ecl_math + ) + # Hack just to make sure our tests pass if we're using external eigen3 + # Note that this is covered for dependant packages + # in the manifest.xml externally via a hunt for pkg-config + if ( EIGEN3_INCLUDE_DIR ) + set_target_properties(ecl_test_linear_algebra_${test_name} PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS} -I${EIGEN3_INCLUDE_DIR}") + endif() + endif() +endmacro() + +############################################################################## +# Google Tests +############################################################################## + +ecl_linear_algebra_add_gtest(plugin) +ecl_linear_algebra_add_gtest(formatters) +ecl_linear_algebra_add_gtest(interpolators) + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/formatters.cpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/formatters.cpp new file mode 100644 index 0000000..b145b64 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/formatters.cpp @@ -0,0 +1,101 @@ +/** + * @file /ecl_linear_algebra/src/test/formatters.cpp + * + * @brief Unit test the matrix formatters. + * + * Can't easily do gtests on this as its just streaming to cout. + * + * @date September 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/linear_algebra.hpp" +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Format; +using ecl::linear_algebra::Matrix2f; +using ecl::linear_algebra::Matrix2d; +using ecl::linear_algebra::Vector2d; +using ecl::linear_algebra::MatrixFormatter; +using ecl::linear_algebra::FloatMatrixFormatter; + +/***************************************************************************** +** Main program +*****************************************************************************/ + +TEST(FormattersTest,autoSucceedNeedsFix) { + SUCCEED(); +} + +int main(int argc, char **argv) { + + Vector2d v; v << 1.0, 2.0; + Matrix2d m; m << 1.0, 2.0, 3.0, 4.134; + Matrix2f mf; mf << 1.0, 2.0, 3.0, 4.134; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " MatrixFormatter" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + FloatMatrixFormatter vector_format; + std::cout << vector_format(v) << std::endl; + FloatMatrixFormatter matrix_format; + std::cout << matrix_format(m) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " MatrixBase::Formatter" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Vector2d::Formatter vector_format2(3); + std::cout << vector_format2(v) << std::endl; + Matrix2d::Formatter matrix_format2; + std::cout << matrix_format2(m) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Format" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Format vector_format3; + std::cout << vector_format3(v) << std::endl; + Format matrix_format3; // Sneaking a test in for floats here + std::cout << matrix_format3(mf) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Temporary/Prm Settings" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + matrix_format.precision(2); + matrix_format.width(-1); + std::cout << "Using perm settings (2,-1):" << std::endl; + std::cout << matrix_format(m) << std::endl; + std::cout << "Using temp settings (3, 6):" << std::endl; + std::cout << matrix_format(m,3,6) << std::endl; + std::cout << "Using perm settings (2,-1):" << std::endl; + std::cout << matrix_format(m) << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); + +} diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/interpolators.cpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/interpolators.cpp new file mode 100644 index 0000000..4d28aee --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/interpolators.cpp @@ -0,0 +1,94 @@ +/** + * @file src/test/interpolators.cpp + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/linear_algebra/sophus.hpp" + +/***************************************************************************** + ** Methods + *****************************************************************************/ + +double getAngle(const Sophus::SE3f& T) { + Eigen::Matrix axis_angle = T.inverse().so3().log(); + // our tests are doing yaws only + return axis_angle(2); +} + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Interpolation, Interpolation) { + Sophus::SE3fFormatter formatter(6,2); + /******************** + ** Frame Poses + ********************/ + Eigen::Matrix3f rotation_matrix_start = Eigen::AngleAxis (1*ecl::pi_2, Eigen::Vector3f::UnitZ ()).matrix(); + Sophus::SE3f start = Sophus::SE3f(rotation_matrix_start, Eigen::Vector3f::UnitY()); + Eigen::Matrix3f rotation_matrix_finish = Eigen::AngleAxis (1*ecl::pi, Eigen::Vector3f::UnitZ ()).matrix(); + Sophus::SE3f finish = Sophus::SE3f(rotation_matrix_finish, Eigen::Vector3f::UnitX()); + std::cout << "Start : " << formatter(start) << std::endl; + std::cout << "Finish : " << formatter(finish) << std::endl; + /******************** + ** Transforms + ********************/ + Sophus::SE3f T_start_rel_world = start.inverse(); + Sophus::SE3f T_finish_rel_world = finish.inverse(); + /******************** + ** Interpolation + ********************/ + //Sophus::Interpolator interpolator(T_start_rel_world, T_finish_rel_world); + Sophus::SlidingInterpolator interpolator(T_start_rel_world, T_finish_rel_world); + for ( unsigned int i = 0; i <= 10; ++i ) { + double t = i*0.1; + Sophus::SE3f T_t_rel_world = interpolator(t); + //EXPECT_NEAR(getAngle(T_t_rel_world), i*0.15708, 0.001); + std::cout << formatter(T_t_rel_world.inverse()) << " [t:" << t << "][axis_angle:" << getAngle(T_t_rel_world) << "]" << std::endl; + } +} + +TEST(Interpolation, TwoDimensionalInterpolation) { + Sophus::SE3fFormatter formatter(6,2); + /******************** + ** Frame Poses + ********************/ + Sophus::SE3f start = Sophus::SE3f(Eigen::Quaternionf::Identity(), Eigen::Vector3f::Zero()); + Eigen::Matrix3f rotation_matrix = Eigen::AngleAxis (-1*ecl::pi_2, Eigen::Vector3f::UnitZ ()).matrix(); + Sophus::SE3f finish = Sophus::SE3f(rotation_matrix, 10*Eigen::Vector3f::UnitX()); + std::cout << "Start : " << formatter(start) << std::endl; + std::cout << "Finish : " << formatter(finish) << " [axis_angle:" << getAngle(finish.inverse()) << "]" << std::endl; + /******************** + ** Transforms + ********************/ + Sophus::SE3f T_start_rel_world = start.inverse(); + Sophus::SE3f T_finish_rel_world = finish.inverse(); + /******************** + ** Interpolation + ********************/ + Sophus::PlanarInterpolator interpolator(T_start_rel_world, T_finish_rel_world); + for ( unsigned int i = 0; i <= 10; ++i ) { + double t = i*0.1; + Sophus::SE3f T_t_rel_world = interpolator(t); + EXPECT_NEAR(getAngle(T_t_rel_world), -1.0*i*0.15708, 0.001); + std::cout << formatter(T_t_rel_world.inverse()) << " [t:" << t << "][axis_angle:" << getAngle(T_t_rel_world) << "]" << std::endl; + } +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + + diff --git a/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/plugin.cpp b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/plugin.cpp new file mode 100644 index 0000000..778de2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_linear_algebra/src/test/plugin.cpp @@ -0,0 +1,47 @@ +/** + * @file /ecl_linear_algebra/src/test.cpp + * + * @brief File comment + * + * File comment + * + * @date 28/07/2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/linear_algebra.hpp" +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::linear_algebra::MatrixXd; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(PluginTest,autoSucceedNeedsFix) { + SUCCEED(); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + MatrixXd matrix(2,2); + matrix << 1.0, 2.0, 3.0, 4.0; + std::cout << matrix << std::endl; + matrix.conservativeResize(4,4); + std::cout << "After resizing.........." << std::endl; + std::cout << matrix << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/.cproject b/ros2_ws/src/ecl_core/ecl_manipulators/.cproject new file mode 100644 index 0000000..0440e7b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/.cproject @@ -0,0 +1,336 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + tests + true + true + true + + + make + clean + true + true + true + + + make + + all + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/.gitignore b/ros2_ws/src/ecl_core/ecl_manipulators/.gitignore new file mode 100644 index 0000000..0dfb25f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/.gitignore @@ -0,0 +1,3 @@ +# test artifacts +linear_interpolation.dat +tension_interpolation.dat diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/.project b/ros2_ws/src/ecl_core/ecl_manipulators/.project new file mode 100644 index 0000000..eae05d4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/.project @@ -0,0 +1,78 @@ + + + ecl_manipulators + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/CMakeLists.txt new file mode 100644 index 0000000..e1a596d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/CMakeLists.txt @@ -0,0 +1,67 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_manipulators) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_geometry REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Installs +############################################################################## + +install( + DIRECTORY scripts + DESTINATION share/${PROJECT_NAME} + PATTERN "CMakeLists.txt" EXCLUDE +) + + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_exceptions + ecl_formatters + ecl_geometry +) +ament_package() + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/mainpage.dox new file mode 100644 index 0000000..99510b6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/mainpage.dox @@ -0,0 +1,198 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This group includes various structures and tools for generating + manipulator trajectories (interpolating methods etc). + +@section CompilingLinking Compiling & Linking + + @code + #include + + // The classes + using ecl::Trajectory; + using ecl::WayPoint; + @endcode + + Since the manipulator classes are templatised headers, there is no + need to directly link (however, it's dependencies will need linking). + +\section usage Usage + + Trajectory generation is usually done either in the joint angle space + or in the cartesian space. All the classes in this library are + configured appropriately via the @ref ecl::ManipulatorAngleType "Angle Type" + enumeration (Cartesian or JointAngle) type used as a template argument. + + @subsection WayPoints + + These are often also called via points or nodes depending + on the context. They are used here as a means of representing the state + of a manipulator at a particular point. A rough sequence of these can be + then utilised to generate an interpolation with a much finer granularity. + + @section jointangleUsage Joint Angle Trajectories + + @subsection jointangleWaypoints WayPoints + + Joint angle waypoints require alot of configuration, so the waypoint class + provides methods for the programmer to manually do so: + + @code + Waypoint<4> waypoint; + waypoint.name("Raised Position"); // String identifier (not req'd). + waypoint.nominalRates(1.0); // Sets a common nominal rate to the next waypoint. + waypoint.nominalRates = 1.0, 1.0, 0.8, 0.8; // Sets specific angular rates to the next waypoint. + waypoint.angles() = 1.57, 1.57, 0, 0; // Joint angle specification. + waypoint.rates() = 1.0, 0, 0, 0; // Rates through a point (only used on first/last waypoints) + waypoint.duration(3.00); // An alternative to setting nominalRates. + @endcode + + The current interpolations are designed to relieve alot of the detail involved in + configuring waypoints and generating trajectories. Depending on the interpolation, + they will often use a heuristic or apply constraints to best solve the following waypoint properties: + + - timestamp - interpolations will often stretch out the sequence to satisfy acceleration bounds. + - velocities - the nominal rates given above are typically used as a 'hint', but are reduced to satisfy constraints. + - accelerations - provided they stay within bounds, accelerations are usually automatically generated, usually with a continuity guarantee. + + Practically, the interpolations use the nominalRates to initialise a guess for the waypoint timestamps. + These are amended later to satisfy other interpolation constraints (such as maximum acceleration). + If you set the nominalRate to 0.0, most interpolations will then look to the duration to set an + initial guess for the waypoint timestamps. + + @subsection jointangleTrajectoryInterpolations Trajectories + + All trajectory generating techniques work on the waypoint classfication given above. As noted above, one goal + towards this is to try and make trajectory generation as smart as possible. I'd rather have it + intelligently automate the generation of the data set on a little information as possible. + Too often, trajectory generation requires alot of fiddling of the underlying data set, or + guessing of parameters such as rates, accelerations and time values. Usually this guessing + has no optimisation involved or intelligent heuristic applied. + + The joint angle trajectory class applies this. It fulfills several features: + - Serves as a waypoint storage container. + - Saves various trajectory-wide parameters (such as joint motor accelerations). + - Allows generation of the trajectory spline functions using one of a various of + interpolation techniques. + - Provides accessors to extract the value of the interpolated trajectories at any point. + + The following code illustrates a sample trajectory generation flow: + @code + WayPoint<2,JointAngles> waypoint; + + waypoint.name("Initial Position"); + waypoint.angles() = 1.0, 1.0; + waypoint.nominalRates(1.0); + trajectory.append(waypoint); + + // more waypoint definitions. + + waypoint.name("End Position"); + waypoint.angles() = 4.0, 4.0; + waypoint.nominalRates(1.0); + trajectory.append(waypoint); + + // set trajectory acceleration bounds + trajectory.maxAccelerations(0.8); // common + // trajectory.maxAccelerations = 0.8, 0.8, 0.6, 0.6; // joint specific bounds + + // interpolations + // trajectory.quinticCubicSplineInterpolation(); // a quintic_polynomial-cubic_spline-quintic_polynomial. + trajectory.tensionSplineInterpolation(4.0); // tension spline with pre and post pseudo waypoints. + // trajectory.smoothLinearSplineInterpolation(); // linear blend with smooth (quintic) corners, pre and post pseudo waypoints. + + // extracting a discretised trajectory + for ( int i = 0; i <= n; ++i ) { + double x = i*(trajectory.duration())/n; + cout << x; + cout << trajectory(0,x); + cout << trajectory.derivative(0,x); + cout << trajectory.dderivative(0,x) << endl; + } + @endcode + + @subsection Interpolations + + Commonly either a linear interpolation with blends or a variant of a cubic spline is used. On a cheap + robot arm though, these have a few problems since the motors suffer greatly from backlash and + inaccuracies. + + - Linear blends define a bang-bang acceleration to generate the trajectory (rough on the motors). + - Cubic splines do not have enough coefficients to ensure y' = y'' = 0 at the trajectory beginning and ending. + - Cubic splines do not ensure maximum acceleration bound constraints. + + To get around this, we utilise a few different ideas to ensure the following problems dont exist. + + - Stretch the interpolations to satisfy maximum acceleration bounds. + - Use a quintic on the first and last segments to ensure resting rates and accelerations. + - Alternatively, apply a pre/post pseudo waypoint and attach very small quintics to the front and back. + - Use C2 continuous splines to avoid bang-bang problems. + + @subsection qcqInterpolation Quintic-Cubic-Quintic Interpolating Trajectories + + For this, we attach a fully quintic polynomial at the front and back ends (first and last waypoints) and + use a natural cubic spline in the middle. The natural cubic spline ensures C2 continuity and provides the + connections to automatically ensure the quintics provide the zero'd boundary conditions. + + Lastly, the interpolation algorithm firstly uses the waypoint nominal rate suggestions to define a + rough time sequence and then uses an iterative technique to stretch the trajectory until the + acceleration bounds are met. + + Note, to configure everything for this interpolation algorithm, you will need: + - Waypoint angles (y's) + - Waypoint nominal rates or durations. + - Trajectory maximum acceleration bound. + + Unfortunately, one problem with this is the quintic will often head in the wrong direction at the + start of the motion so that it can meet whatever velocity and acceleration constraints are set up + by the interior cubic spline at the second waypoint. To make sure this doesn't happen, you need to + tune your waypoints carefully. + + @image html quintic_cubic_quintic_interpolation.png + + @subsection slInterpolation Smoothed Linear Interpolating Trajectories + + This interpolation is like the tension spline at very high tension. It uses linear segments and + quintic corners, as well as applying the same pre-post pseudo waypoint trick to guarantee + resting constraints at the boundaries. It's a good alternative to the tension spline + when you want almost exactly predictable motions rather than natural human like curves. + + To configure everything, proceed as for the quintic-cubic-quintic. + + @image html smooth_linear_interpolation.png + + @subsection qtqInterpolation Tension Interpolating Trajectories + + This interpolation is very similar to the quintic-cubic-quintic except that a tension spline is used + in place of the natural spline and very small quintics are attached at the front and back via pseudo + waypoints located very close to the actual starting and finishing waypoints. + + A tension spline at low tension is just like the cubic (i.e. as + tension -> 0.0, the spline becomes a cubic). By increasing the tension parameter to the interpolation + algorithm, you can effectively tighten the polynomial until it starts looking more like the linear blend. + This tends to provide more predictable motions and the acceleration is more tightly bound to zero + most of the time (cubic spline accelerations will swing around fairly wildly). + + To configure everything, proceed as for the quintic-cubic-quintic. The only addition is to supply + a tension parameter when calling the interpolation algorithm. + + @image html tension_interpolation.png + + +\section unitTests Unit Tests + + - src/test/waypoints.cpp + - src/test/trajectories.cpp + +\section ChangeLog + + - Jul 09 : ecl::Trajectory has a smooth linear spline interpolator. + - Jul 09 : ecl::Trajectory has a tension spline interpolator. + - May 09 : ecl::Trajectory has a quintic-cubic-quintic spline interpolator. + - May 09 : ecl::Trajectory formulation with waypoints finalised. + - May 09 : ecl::WayPoint structure finalised. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/namespaces.dox new file mode 100644 index 0000000..4f57a68 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/namespaces.dox @@ -0,0 +1,8 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/quintic_cubic_quintic_interpolation.png b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/quintic_cubic_quintic_interpolation.png new file mode 100644 index 0000000..2e9c5a8 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/quintic_cubic_quintic_interpolation.png differ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/smooth_linear_interpolation.png b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/smooth_linear_interpolation.png new file mode 100644 index 0000000..e238d21 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/smooth_linear_interpolation.png differ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/tension_interpolation.png b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/tension_interpolation.png new file mode 100644 index 0000000..79734e5 Binary files /dev/null and b/ros2_ws/src/ecl_core/ecl_manipulators/doxygen/tension_interpolation.png differ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/include/CMakeLists.txt new file mode 100644 index 0000000..aac64a1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..d52ab98 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(manipulators) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators.hpp b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators.hpp new file mode 100644 index 0000000..6a7822c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators.hpp @@ -0,0 +1,28 @@ +/** + * @file /include/ecl/manipulators.hpp + * + * @brief Mathematical tools for robotic manipulators. + * + * Mathematical tools for robotic manipulators. Later I want to move this to + * its own ecl library. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MANIPULATORS_HPP_ +#define ECL_MANIPULATORS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "manipulators/types.hpp" +#include "manipulators/waypoint.hpp" +#include "manipulators/trajectory.hpp" + + +#endif /*ECL_MANIPULATORS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/CMakeLists.txt new file mode 100644 index 0000000..e34ccda --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/manipulators) diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/trajectory.hpp b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/trajectory.hpp new file mode 100644 index 0000000..a1814aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/trajectory.hpp @@ -0,0 +1,403 @@ +/** + * @file /include/ecl/manipulators/trajectory.hpp + * + * @brief Trajectory generation for manipulators. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MANIPULATORS_TRAJECTORY_HPP_ +#define ECL_MANIPULATORS_TRAJECTORY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "types.hpp" +#include "waypoint.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Trajectory][PrimaryTemplate] +*****************************************************************************/ +/** + * @brief Primary template for manipulator trajectories. + * + * This is not intended to be used directly, it just provides the primary + * template for specialisations of the type enum. + * + * @tparam Type : manipulator state representation type (either joint or cartesian based). + * + * @sa Trajectory. + **/ +template +class Trajectory { + private: + /** + * @brief Unreachable constructor. + * + * Constructor, declared privately to ensure that this class + * cannot be instantiated directly. + */ + Trajectory () {}; + virtual ~Trajectory () {}; +}; + +/***************************************************************************** +** Interface [Trajectory][JointAngles] +*****************************************************************************/ +/** + * @brief Joint angle based manipulator trajectory. + * + * Joint angle based manipulator trajectory. Construction simply provides an + * empty instantiation for the trajectory. You must + * + * - Populate it with desired way points (use the append method). + * - Generate the interpolation (use one of the interpolators). + * + * to fully define the resulting trajectory. + * + * @sa Trajectory. + **/ +template <> +class Trajectory { + public: + /** + * @brief Default constructor, only (optionally) configures the trajectory name. + * + * @param name_identifier : string identifier for the trajectory name. + */ + Trajectory(const char* name_identifier = "") : + name(name_identifier) + {} + /** + * @brief Configures the joint dimension, and also (optionally) the trajectory name. + * + * @param dimension : number of joints in this trajectory. + * @param name_identifier : string identifier for the trajectory name. + */ + Trajectory(const unsigned int& dimension, const char* name_identifier = "") : + name(name_identifier), + spline_functions(dimension), + max_accelerations(Array::Constant(dimension,0.0)) + {} + + /** + * @brief Default destructor. + * + * Cleans up the memory allocations for the spline functions. + */ + virtual ~Trajectory() { clearSplines(); waypoints.clear(); } + /** + * @brief Clear the waypoints and splines. + */ + void clear() { clearSplines(); waypoints.clear(); } + /** + * @brief Number of waypoints in the trajectory. + * + * @return unsigned int : number of waypoints stored in the trajectory. + */ + unsigned int size() const { return waypoints.size(); } + + /** + * @brief Dimension, or degrees of freedom for the trajectory. + * + * This is the number of joints being interpolated by the trajectory. + * @return int : number of joints. + */ + unsigned int dimension() const { return max_accelerations.size(); } + + /** + * @brief Reset the dimension, or degrees of freedom for the trajectory. + * + * Reset the number of joints being interpolated by the trajectory. + * + * @param dim : number of joints in this trajectory. + */ + void redimension(const unsigned int &dim) { + clear(); + spline_functions.resize(dim); + max_accelerations = Array::Constant(dim,0.0); + } + + /** + * @brief Appends a waypoint to the trajectory specification. + * + * This is the only means of configuring waypoints for the trajectory. + * Note that you cannot delete them, nor insert them into the middle + * of the waypoint sequence. These functions are not really necessary + * and just complicate the interface, but keep it in mind when programming + * for trajectories. + * + * @exception : StandardException : throws if waypoint dimension doesn't match. + */ + void append(const WayPoint &waypoint) { + ecl_assert_throw(dimension() == waypoint.dimension(), StandardException(LOC, InvalidInputError, "Mismatched trajectory and waypoint dimensions.") ); + waypoints.push_back(waypoint); + } + + /** + * @brief Get the last waypoint in the trajectory. + * + * This is just a utility function for checking the last waypoint in the + * trajectory. + * + * @return const WayPoint& : const handle to the last waypoint in the traectory. + */ + WayPoint& last() { + return waypoints.back(); + } + + /** + * @brief Const version of the last waypoint in the trajectory. + * + * This is just a utility function for checking the last waypoint in the + * trajectory. + * + * @return const WayPoint& : const handle to the last waypoint in the traectory. + */ + const WayPoint& last() const { + return waypoints.back(); + } + /** + * @brief Get a handle to the specified waypoint. + * + * This is just a utility function for retrieving a waypoint (const version). + * + * @param index : index of the waypoint to get a handle to. + * @return WayPoint : the waypoint, if index was correct. + * + * @exception : StandardException : throws if index is outside the number of stored waypoints [debug mode only]. + */ + const WayPoint& waypoint(const unsigned int &index) { + ecl_assert_throw(index < waypoints.size(), StandardException(LOC, OutOfRangeError, "The index used exceeds the number of waypoints stored in the trajectory.")); + return waypoints[index]; + } + + /** + * @brief Generate a tension spline interpolation from the specified waypoints. + * + * This generates an interpolation across the waypoints with the following characteristics. + * + * - Interpolation begins and ends with y' = y'' = 0. + * - C2 continuous. + * - Spline functions are connected as follows: + * - Quintic Polynomial : needed to ensure y' = y'' = 0. + * - Tension Spline : guarantees C2 continuity across the interpolation. + * - Quintic Polynomial : needed to ensure y' = y'' = 0. + * + * The quintics are generated from internally generated pseudo-waypoints to ensure that the + * initial and final resting conditions are met. + * + * Before you call this function, make sure the following requirements are met. + * - @ref ecl::WayPoint "Waypoints" are assigned with following data set: + * - angles (y) + * - nominal rates (i.e. estimated velocities) OR durations + * - maximum accelerations have been set (via this classes maxAccelerations methods) + */ + void tensionSplineInterpolation(const double &tension); + /** + * @brief Generate a smoothed linear spline interpolation from the specified waypoints. + * + * This generates an interpolation across the waypoints with the following characteristics. + * + * - Interpolation begins and ends with y' = y'' = 0. + * - C2 continuous. + * - Spline functions are connected as follows: + * - Quintic Polynomial : needed to ensure y' = y'' = 0. + * - Smooth Linear Spline : composition of segments and corners. + * - Quintic Polynomial : needed to ensure y' = y'' = 0. + * + * The quintics are generated from internally generated pseudo-waypoints to ensure that the + * initial and final resting conditions are met. + * + * Before you call this function, make sure the following requirements are met. + * - @ref ecl::WayPoint "Waypoints" are assigned with following data set: + * - angles (y) + * - nominal rates (i.e. estimated velocities) OR durations + * - maximum accelerations have been set (via this classes maxAccelerations methods) + */ + void linearSplineInterpolation(); + + /** + * @brief Access the value of the joint trajectory at the specified point. + * @param joint : specifies the joint you are interested in. + * @param time : the time at which you wish to calculate the value for. + * @return double : the value of the specified joint trajectory at x. + * @exception : StandardException : throws if input time value is outside the domain [debug mode only]. + */ + double operator ()(const unsigned int& joint, const double& time ); + /** + * @brief Access the derivative of the joint trajectory at the specified point. + * @param joint : specifies the joint you are interested in. + * @param time : the time at which you wish to calculate the value for. + * @return double : the derivative of the specified joint trajectory at x. + * @exception : StandardException : throws if input time value is outside the domain [debug mode only]. + */ + double derivative(const unsigned int& joint, const double& time ); + /** + * @brief Access the 2nd derivative of the joint trajectory at the specified point. + * @param joint : specifies the joint you are interested in. + * @param time : the time at which you wish to calculate the value for. + * @return double : the 2nd derivative of the specified joint trajectory at x. + * @exception : StandardException : throws if input time value is outside the domain [debug mode only]. + */ + double dderivative(const unsigned int& joint, const double& time ); + + /********************* + ** Accessors + **********************/ + /** + * @brief Handle to the max accelerations array, use to initialise the polynomial. + * + * This returns a handle to the max accelerations array. Use this with + * the comma initialiser to conveniently set the polynomial. + * + * @code + * Trajectory<2> trajectory; + * trajectory.maxAccelerations() = 0.8,0.6; + * @endcode + * + * @return Array& : reference to the max accelerations array. + **/ + Array& maxAccelerations() { return max_accelerations; }; + /** + * @brief Configure the entire trajectory with a uniform max acceleration bound. + * + * Configure the entire trajectory with a uniform max acceleration bound + * (i.e. each joint's acceleration is limited similarly). + * + * @param max_acceleration : the uniform maximum acceleration bound to use. + */ + void maxAccelerations(const double &max_acceleration) { + for ( unsigned int i = 0; i < dimension(); ++i ) { + max_accelerations[i] = max_acceleration; + } + } + /** + * @brief Non-modifiable handle to the max accelerations array. + * + * @return const Array& : non-modifiable reference to the max accelerations array. + **/ + const Array& maxAccelerations() const { return max_accelerations; }; + + /****************************************** + ** Streaming + *******************************************/ + /** + * @brief Streaming output insertion operator for for waypoints. + * + * Streaming output insertion operator for waypoints. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param trajectory : the trajectory. + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, Trajectory &trajectory); + + /****************************************** + ** Parameters + *******************************************/ + /** + * @brief Total trajectory duration (in seconds). + * + * Trajectory duration (in seconds). + * + * @return const double& : the time required for the entire trajectory. + **/ + const double& duration() const { return trajectory_duration; } + Parameter name; /**< @brief String name identifier. **/ + + private: + std::vector< WayPoint > waypoints; + Array< std::vector > spline_functions; + Array< double> max_accelerations; + double trajectory_duration; + + /** + * @brief Clean up the memory allocated to the spline functions. + * + * This is used internally by the various interpolation algorithms. + */ +public: + void clearSplines(); + /** + * Unlike the other generators, this generates the spline over all the waypoints. + * It is not used in combination with another spline function. + */ + Array generateLinearSplines(); + /** + * This creates the tension splines across waypoints w_0 -> w_n for the + * quinticTensionInterpolation. Note that the quintic tension will + * insert pseudo points at the beginning and end later which will forcibly + * modify the behaviour of the tension spline endpoints for specific boundary conditions. + */ + Array generateTensionSplines(const double& tension, const double initial_time = 0.0); + /** + * This checks various properties of the waypoints to make sure they're valid. + * Generally, this is used by the interpolations, who then throw if something's + * gone wrong. + */ + bool validateWaypoints(unsigned int min_no_waypoints); + /** + * This uses the nominal rates to guess durations between each waypoint. + * Generally, this is used by the interpolations, who then throw if something's + * gone wrong. + */ + bool initialiseWaypointDurations(); + /** + * This is a convenient function for interpolation members to use to + * update the duration with the latest calculation determined from + * the sum of the waypoint durations. This is oft used since the + * interpolations will often adjust the waypoint durations while + * interpolating. + */ + void updateDuration(); +}; + +/***************************************************************************** +** Implementation [Trajectory][Streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, Trajectory &trajectory) { + + ecl_compile_time_concept_check(StreamConcept); + + for (unsigned int i = 0; i < trajectory.waypoints.size(); ++i ) { + ostream << "Waypoint " << i << "\n"; + ostream << trajectory.waypoints[i] << "\n"; + } + ostream.flush(); + return ostream; +} + +} // namespace ecl + +#endif /* ECL_MANIPULATORS_TRAJECTORY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/types.hpp b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/types.hpp new file mode 100644 index 0000000..3920928 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/types.hpp @@ -0,0 +1,39 @@ +/** + * @file /include/ecl/manipulators/types.hpp + * + * @brief Type definitions for manipulators. + * + * @date May 2008 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MANIPULATORS_TYPES_HPP_ +#define ECL_MANIPULATORS_TYPES_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Enums +*****************************************************************************/ + +/** + * @brief Angle usage type for the manipulator trajectory definitions. + * + * Angle usage type for the manipulator. Most simple manipulators simply use + * joint angles - more complicated manipulators that have to interact with + * the environment require measurements of the end effector in cartesians. + */ +enum ManipulatorAngleType { + JointAngles, /**< @brief Joint angle representations are being used. **/ + Cartesians /**< @brief Cartesian representations are being used. **/ +}; + +} // namespace ecl + +#endif /* ECL_MANIPULATORS_TYPES_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/waypoint.hpp b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/waypoint.hpp new file mode 100644 index 0000000..8fc2a11 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/include/ecl/manipulators/waypoint.hpp @@ -0,0 +1,418 @@ +/** + * @file /include/ecl/manipulators/waypoint.hpp + * + * @brief Waypoint definitions for various manipulator contexts. + * + * Waypoints designating manipulator position and orientation in free space. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MANIPULATORS_WAYPOINT_HPP_ +#define ECL_MANIPULATORS_WAYPOINT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "types.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Class [WayPoint] +*****************************************************************************/ +/** + * @brief Primary template for waypoints. + * + * This is not intended to be used directly, it just provides the primary + * template for specialisations of the type enum. + * + * @tparam Type : the type of waypoint (either joint or cartesian based). + * + * @sa WayPoint. + */ +template +class WayPoint { + private: + /** + * @brief Unreachable constructor. + * + * Constructor, declared privately to ensure that this class + * cannot be instantiated directly. + */ + WayPoint() {}; +}; + +/***************************************************************************** +** Class [WayPoint] +*****************************************************************************/ +/** + * @brief WayPoint specialisation with joint (motor) angle storage format. + * + * This class can be used to store waypoints in joint/motor angle format. + * It is not especially useful for navigational waypoints, but often + * the only storage format required for robotic arm tasks. This is intended + * to be a very light class. + * + * @tparam N : no. of degrees of freedom for this waypoint. + * + * @sa @ref WayPoint "WayPoint". + **/ +template <> +class WayPoint +{ + public: + typedef Array JointDataArray; /**< @brief A convenient typedef to the underlying storage array. **/ + + + /****************************************** + ** Constructors + *******************************************/ + /** + * @brief Default constructor. + * + * Configures the waypoint to be of zero dimension. Make sure you use the + * redimension function later to set the dimension. + **/ + WayPoint() : + name(""), + duration(0.0), + rates_configured(false), + accelerations_configured(false) + {} + + /** + * @brief Configures the waypoint for a specific dimension. + * + * Configuring the waypoint requires setting of many required and optional + * parameters, some of which are initialised at construction and some of + * which are later calculated. This is usually beyond the scope of defining a simple + * constructor (though a very simple configuration is deployed through + * the alternative constructor here). Consequently, manual configuration + * must be utilised if you use this constructor: + * @code + * Waypoint waypoint(4); + * waypoint.name("Raised Position"); // String identifier (not req'd). + * waypoint.nominalRates(1.0); // Sets a common nominal rate to the next waypoint. + * waypoint.nominalRates << 1.0, 1.0, 0.8, 0.8; // Sets specific angular rates to the next waypoint. + * waypoint.angles() << 1.57, 1.57, 0, 0; // Joint angle specification. + * @endcode + * Angle rates and accelerations are currently only configured by the interpolation techniques + * that act on the waypoints. At some stage though, this may change if we want more flexible, + * higher order interpolating functionalities. + * @code + * waypoint.rates() << 1.0, 1.0, 0.5, 0.5; // Joint angle rates specification. + * waypoint.accelerations() << 0.0, 0.0, 0.0, 0.0; // Joint angle accelerations specification. + * waypoint.duration(3.00); // Useful if you set a nominalRate of 0.0. + * @endcode + */ + WayPoint(const unsigned int &dimension) : + name(""), + duration(0.0), + rates_configured(false), + accelerations_configured(false), + angle_positions(JointDataArray::Constant(dimension,0.0)), + angle_rates(JointDataArray::Constant(dimension,0.0)), + angle_accelerations(JointDataArray::Constant(dimension,0.0)), + nominal_rates(JointDataArray::Constant(dimension,1.00)) + {} + + /** + * @brief Copy constructor. + * + * @param waypoint + * @return + */ + WayPoint( const WayPoint &waypoint) : + name(waypoint.name()), + duration(waypoint.duration()), + rates_configured(waypoint.rates_configured()), + accelerations_configured(waypoint.accelerations_configured()), + angle_positions(waypoint.angle_positions), + angle_rates(waypoint.angle_rates), + angle_accelerations(waypoint.angle_accelerations), + nominal_rates(waypoint.nominal_rates) + {} + + virtual ~WayPoint() {} + + /****************************************** + ** Configuration + *******************************************/ + /** + * @brief Return the waypoint dimension. + * + * The number of joints used to compose the waypoint. + * + * @return const unsigned int& the dimension of the waypoint. + **/ + unsigned int dimension() const { return angle_positions.size(); } + + /** + * @brief + * @param dimension + */ + void redimension(const unsigned int &dimension) { + angle_positions = JointDataArray::Constant(dimension,0.0); + angle_rates = JointDataArray::Constant(dimension,0.0); + angle_accelerations = JointDataArray::Constant(dimension,0.0); + nominal_rates = JointDataArray::Constant(dimension,0.0); + } + /** + * @brief Handle to the joint angle array. + * + * Supplies a handle to the joint angle array which can be used + * to set/modify joint angle information (can use the comma initialiser). + * + * Note a convenient way to set the angle information + * is to use the comma initialiser of the underlying angle array: + * @code + * waypoint.angles() = 1.57, 1.57, 0, 0; + * @endcode + * + * @return Array& : handle to the joint angle array. + **/ + Array& angles() { return angle_positions; } + /** + * The const version of angles() + * @return + */ + const Array& angles() const { return angle_positions; } + + /** + * @brief Handle to the joint angle rates array. + * + * Supplies a handle to the joint angle rates array which can be used + * to set/modify joint angle rate information (can use the comma initialiser). + * + * The joint angle rates represent the specified angular rate that must be + * attained as a trajectory moves through this waypoint. It is not always + * necessary depending on the type of interpolation being used (cubic spline vs + * quintic spline) and the location of the waypoint in the trajectory (boundary vs internal). + * + * When using this method, the waypoint is flagged as having had its angular + * rates configured. + * + * Note a convenient way to set the information + * is to use the comma initialiser of the underlying angle array: + * @code + * waypoint.rates() << 1.0, 1.0, 0, 0; + * @endcode + * + * I don't actually really like this - because we've actually got + * no real guarantee that the lazy bastard outside the class + * actually configured the values. + * + * @return Array& : handle to the joint angle rates array. + **/ + Array& rates() { + rates_configured(true); + return angle_rates; + } + /** + * The const version of rates(). + * @return + */ + const Array& rates() const{ + return angle_rates; + } + + /** + * @brief Handle to the joint angle accelerations array. + * + * Supplies a handle to the joint angle accelerations array which can be used + * to set/modify joint angle acceleration information (can use the comma initialiser). + * + * The joint angle accelerations represent the specified angular acceleration that must be + * attained as a trajectory moves through this waypoint. It is not always + * necessary depending on the type of interpolation being used (cubic spline vs + * quintic spline) and the location of the waypoint in the + * trajectory (boundary vs internal). + * + * When using this method, the waypoint is flagged as having had its angular + * accelerations configured. + * + * Note a convenient way to set the information + * is to use the comma initialiser of the underlying angle array: + * @code + * waypoint.accelerations() = 1.0, 1.0, 0, 0; + * @endcode + * + * @return Array& : handle to the joint angle accelerations array. + **/ + Array& accelerations() { + accelerations_configured(true); + return angle_accelerations; + } + /** + * The const version of accelerations() + * @return + */ + const Array& accelerations() const { + return angle_accelerations; + } + + /** + * @brief Handle to the nominal angle rates array. + * + * Supplies a handle to the nominal rates array which can be used + * to set/modify the individual nominal rates (can use the comma initialiser). + * + * The nominal rates represent the recommended (which may be + * ignored by the interpolation method) average angular rate to be used + * over the ensuing segment until the next waypoint is reached. + * + * Note a convenient way to set the values + * is to use the comma initialiser of the underlying array: + * @code + * waypoint.nominalRates() = 1.00, 1.00, 0.60, 0.60; + * @endcode + * + * @return Array>& : handle to the maximum rates array. + **/ + Array& nominalRates() { return nominal_rates; } + /** + * @brief Configures the nominal rates with a common value. + * + * Configures the nominal angular rate the next segment of each joint + * to a common value. + * + * @param nom_rate : the blanket nominal angular rate to set for each joint. + */ + void nominalRates(double nom_rate) { + for ( unsigned int i = 0; i < nominal_rates.size(); ++i) { + nominal_rates[i] = nom_rate; + } + } + + /** + * @brief Equality operator for waypoints. + * + * This is useful as a quick check to see if one waypoint doesn't match + * another. + * + * @param other : the waypoint to check against. + * @return bool : true if all angles are equal, false otherwise. + */ + bool operator==(const WayPoint& other) const { + for ( unsigned int i = 0; i < angle_positions.size(); ++i ) { + if ( angle_positions[i] != other.angle_positions[i] ) { + return false; + } + } + return true; + } + + /** + * @brief Inequality operator for waypoints. + * + * This is useful as a quick check to see if one waypoint doesn't match + * another. + * + * @param other : the waypoint to check against. + * @return bool : true if not all angles are equal, false otherwise. + */ + bool operator!=(const WayPoint& other) const { + for ( unsigned int i = 0; i < angle_positions.size(); ++i ) { + if ( angle_positions[i] != other.angle_positions[i] ) { + return true; + } + } + return false; + } + + /** + * @brief Approximately operator for waypoints. + * + * This is useful as a quick check to see if one waypoint is very similar + * to another. It returns false if any individual angle difference (not the + * sum) is greater than the supplied epsilon. + * + * @param other : the waypoint to check against. + * @param epsilon : approximate to this value of approximateness. + * @return bool : true if all angles are approximately equal, false otherwise. + */ + bool approx(const WayPoint &other, const double& epsilon = 0.01) { + for ( unsigned int i = 0; i < angle_positions.size(); ++i ) { + if ( std::fabs(angle_positions[i] - other.angle_positions[i]) > epsilon ) { + return false; + } + } + return true; + } + + /****************************************** + ** Streaming + *******************************************/ + /** + * @brief Streaming output insertion operator for for waypoints. + * + * Streaming output insertion operator for waypoints. + * + * @tparam OutputStream : the type of stream being used. + * + * @param ostream : the output stream being used. + * @param waypoint : the waypoint. + * @return OutputStream : the output stream. + */ + template + friend OutputStream& operator << (OutputStream &ostream, WayPoint &waypoint); + + /****************************************** + ** Parameters + *******************************************/ + Parameter name; /**< @brief String name identifier. **/ + Parameter duration; /**< @brief Timestamp for this waypoint. **/ + Parameter rates_configured; /**< @brief Rates have been configured for this waypoint. **/ + Parameter accelerations_configured; /**< @brief Accelerations have been configured for this waypoint. **/ + + private: + JointDataArray angle_positions; + JointDataArray angle_rates; // this is rates *at* the point, currently unused by ycs stuff, but might be useful + JointDataArray angle_accelerations; + JointDataArray nominal_rates; // this is rough rates between points (i.e. slopes) +}; + +/***************************************************************************** +** Implementation [WayPoint][Streaming] +*****************************************************************************/ + +template +OutputStream& operator << (OutputStream &ostream, WayPoint &waypoint) { + + Format< Array > format; format.precision(2); format.width(6); + if ( waypoint.name() != "" ) { + ostream << " Name : " << waypoint.name() << "\n"; + } + ostream << " Angles : " << format(waypoint.angle_positions) << "\n"; + if (waypoint.rates_configured()) { + ostream << " Rates : " << format(waypoint.angle_rates) << "\n"; + } + if (waypoint.accelerations_configured()) { + ostream << " Accelerations : " << format(waypoint.angle_accelerations) << "\n"; + } + ostream << " Nominal Rates : " << format(waypoint.nominal_rates) << "\n"; + ostream.flush(); + return ostream; +} + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +//typedef Waypoint JointAngleWaypoint; /**< @brief Convenient typedef for joint angle waypoints. **/ + +} // namespace ecl + +#endif /* ECL_MANIPULATORS_WAYPOINT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/package.xml b/ros2_ws/src/ecl_core/ecl_manipulators/package.xml new file mode 100644 index 0000000..240b60e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/package.xml @@ -0,0 +1,40 @@ + + + ecl_manipulators + 1.2.1 + + Deploys various manipulation algorithms, currently just + feedforward filters (interpolations). + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_manipulators + https://github.com/stonier/ecl_manipulation + https://github.com/stonier/ecl_manipulation/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_build + ecl_license + ecl_exceptions + ecl_geometry + ecl_formatters + + ecl_build + ecl_license + ecl_exceptions + ecl_geometry + ecl_formatters + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/scripts/Makefile b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/Makefile new file mode 100644 index 0000000..7959daa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/Makefile @@ -0,0 +1,33 @@ +XOPTIONS=-geometry 1024x1024 -persist -background white +FILE=./test.dat +#FILE=../resources/waykook/tasks/test.dat +ACCEL_CONSTRAINT=-a 5 +PWD=$(shell pwd) + +linear: data + gnuplot ${XOPTIONS} linear.x11 + +tension: data + gnuplot ${XOPTIONS} tension.x11 + +data: compile + $(PWD)/../bin/test_trajectories + +compile: + @if [ ! -f ../bin/test_trajectories ]; then \ + make -C $(PWD)/.. tests; \ + fi + +clean: + rm *.dat + +help: + @echo "This generates the test programs, writes some output to disk" + @echo "and finally calls gnuplot. Valid targets include:" + @echo "" + @echo " linear : plot the linear interpolations." + @echo " tension: plot the tension interpolations." + @echo "" + + +.PHONY: help clean compile data linear tension diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/scripts/linear.x11 b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/linear.x11 new file mode 100644 index 0000000..d18985e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/linear.x11 @@ -0,0 +1,36 @@ +# For png output. +#set terminal png +#set output 'linear_interpolations.png' + +# For x11 output +set terminal x11 + +set nokey +set autoscale +set xlabel "t" + +set multiplot + +set size 0.50,0.50 + +set origin 0.25,0.50 +set title "Positions" +set ylabel "theta" +plot "linear_interpolation.dat" using 1:2 with lines, \ + "linear_interpolation.dat" using 1:5 with lines + +set origin 0.0,0.00 +set title "Velocities" +set ylabel "theta_dot" +plot "linear_interpolation.dat" using 1:3 with lines, \ + "linear_interpolation.dat" using 1:6 with lines + +set origin 0.50,0.00 +set title "Accelerations" +set ylabel "theta_ddot" +plot "linear_interpolation.dat" using 1:4 with lines, \ + "linear_interpolation.dat" using 1:7 with lines + +unset multiplot # some platforms wont actually draw until you do this + + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/scripts/tension.x11 b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/tension.x11 new file mode 100644 index 0000000..13dc038 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/scripts/tension.x11 @@ -0,0 +1,28 @@ +set terminal x11 +set nokey +set autoscale +set xlabel "t" + +set multiplot + +set size 0.50,0.50 + +set origin 0.25,0.50 +set title "Positions" +set ylabel "theta" +plot "tension_interpolation.dat" using 1:2 with lines, \ + "tension_interpolation.dat" using 1:5 with lines + +set origin 0.0,0.00 +set title "Velocities" +set ylabel "theta_dot" +plot "tension_interpolation.dat" using 1:3 with lines, \ + "tension_interpolation.dat" using 1:6 with lines + +set origin 0.50,0.00 +set title "Accelerations" +set ylabel "theta_ddot" +plot "tension_interpolation.dat" using 1:4 with lines, \ + "tension_interpolation.dat" using 1:7 with lines + +unset multiplot # some platforms wont actually draw until you do this \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/src/CMakeLists.txt new file mode 100644 index 0000000..25de5da --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/CMakeLists.txt @@ -0,0 +1,10 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(lib) +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/CMakeLists.txt new file mode 100644 index 0000000..761513f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/CMakeLists.txt @@ -0,0 +1,36 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Install +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries(${PROJECT_NAME} + ecl_exceptions::ecl_exceptions + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/trajectory.cpp b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/trajectory.cpp new file mode 100644 index 0000000..93b36b7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/trajectory.cpp @@ -0,0 +1,827 @@ +/** + * @file /ecl_manipulators/src/lib/trajectory.cpp + * + * @brief Implementation of joint angle trajectories. + * + * @date October 2010 + **/ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include // has to be first (eigen stdvector defn). +#include "../../include/ecl/manipulators/waypoint.hpp" +#include "../../include/ecl/manipulators/trajectory.hpp" +#include +#include +#include + +/***************************************************************************** + ** Debug Macros + *****************************************************************************/ + +//#define DEBUG_LINEAR_INTERPOLATION +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Implementation [Trajectory][QuinticTensionSplineInterpolation] + *****************************************************************************/ + +void Trajectory::tensionSplineInterpolation(const double &tension) +{ + bool result; + unsigned int n = waypoints.size() - 1; // n = number of segments + + // who the hell made the constraint that this should be 5, shouldn't we only need 3 since we calculate 2 more pseudo points? + ecl_assert_throw( + n+1 >= 5, + StandardException(LOC,ConfigurationError,"Not enough waypoints for a tension spline interpolation (must be >= 5).")); + + result = validateWaypoints(5); + ecl_assert_throw( + result, + StandardException(LOC,ConfigurationError,"Not all the waypoint maximum rates have been specified correctly (must be > 0.0).")); + + result = initialiseWaypointDurations(); + ecl_assert_throw( result, + StandardException(LOC,ConfigurationError,"A waypoint was configured with a zero duration.")); + + /****************************************** + ** Reserve Spline Storage Space + *******************************************/ + clearSplines(); // Clean up any pre-existing definition. + for (unsigned int j = 0; j < dimension(); ++j) + { + spline_functions[j].resize(3, NULL); + } + Array tension_splines(dimension()); + Array leading_quintics(dimension()), trailing_quintics(dimension()); + + /****************************************** + ** Roughly Generate Tension Spline + *******************************************/ + bool splines_constrained = false; + while (!splines_constrained) + { + tension_splines = generateTensionSplines(tension, 0.0); + /********************* + ** Check Max Accel + **********************/ + Array domain = tension_splines[0].domain(); + splines_constrained = true; // This changes to false if we break the max accel constraint + // - tension splines have high accelerations at the joins. + // - inbetween the joins, the acceleration goes towards zero. + // - so we just check the size of the acceleration at the joins to find trouble spots. + for (unsigned int i = 1; i < domain.size() - 1; ++i) + { // Natural spline, first and last accelerations are always zero, so dont worry about them + for (unsigned int j = 0; j < dimension(); ++j) + { + double accel = fabs(tension_splines[j].dderivative(domain[i])); + /********************* + ** Debugging + **********************/ +// std::cout << "Accel checking" << std::endl; +// std::cout << " Domain: " << domain << std::endl; +// std::cout << " Accel[" << i << "," << j << "]: " << accel << std::endl; +// sleep(1); + if (accel > max_accelerations[j]) + { + splines_constrained = false; + double slope_before = fabs( + (waypoints[i].angles()[j] - waypoints[i - 1].angles()[j]) / waypoints[i - 1].duration()); + double slope_after = fabs( + (waypoints[i + 1].angles()[j] - waypoints[i].angles()[j]) / waypoints[i].duration()); +// std::cout << " Slope_Before[" << i << "," << j << "]: " << slope_before << std::endl; +// std::cout << " Slope_After [" << i << "," << j << "]: " << slope_after << std::endl; + if (slope_before > slope_after) + { + waypoints[i - 1].duration(waypoints[i - 1].duration() * 1.1); // 10% increase + } + else + { + waypoints[i].duration(waypoints[i].duration() * 1.1); // 10% increase + } +// i = domain.size(); // Force it to restart <-- This doesn't actually work so well - dampen the whole curve at once instead of gradually from one end! + break; + } + } + } + } + /****************************************** + ** Check rates are set for head/tail + *******************************************/ + // Note that we may yet change values[1] and values[n+1] when fixing the pseudo points below + // Set them all to zero (default option, i.e. starting at rest). + if (!waypoints[0].rates_configured()) + { + waypoints[0].rates() = WayPoint::JointDataArray::Constant(waypoints[0].dimension(), 0.0); + } + if (!waypoints[n].rates_configured()) + { + waypoints[n].rates() = WayPoint::JointDataArray::Constant(waypoints[n].dimension(), 0.0); + } + + /****************************************** + ** Make the pre pseudo point. + *******************************************/ + double leading_quintic_time = 0.0; + bool quintic_constrained = false; + while (!quintic_constrained) + { + quintic_constrained = true; + for (unsigned int i = 1; i <= 5; ++i) + { + double t = i * waypoints[0].duration() / 10; + // move the tension spline to the right, i.e. give us some space to insert a quintic + tension_splines = generateTensionSplines(tension, t); // t <-- is the initial time to start the tension spline + for (unsigned int j = 0; j < dimension(); ++j) + { + // find the right side boundary conditions for the quintic we want to insert + double y_dot = tension_splines[j].derivative(2 * t); + double y = tension_splines[j](2 * t); + // the left side boundary conditions for the quintic + double y_0 = waypoints[0].angles()[j]; + double y_0_dot = waypoints[0].rates()[j]; + leading_quintics[j] = QuinticPolynomial::Interpolation(0.0, y_0, y_0_dot, 0.0, 2 * t, y, y_dot, 0.0); + + /********************* + ** Debugging + **********************/ +// std::cout << "Pre Pseudo Point" << std::endl; +// std::cout << " Domain: " << tension_splines[0].domain() << std::endl; +// std::cout << " y[" << i << "," << j << "] : " << y << std::endl; +// std::cout << " y_dot[" << i << "," << j << "] : " << ydot << std::endl; +// double accel_max = fabs( Maximum()(0.0,2*t,leading_quintics[j].derivative().derivative())); +// if ( accel_max < fabs( Minimum()(0.0,2*t,leading_quintics[j].derivative().derivative())) ) { +// accel_max = fabs( Minimum()(0.0,2*t,leading_quintics[j].derivative().derivative())); +// } +// std::cout << " accel[" << i << "," << j << "] : " << accel_max << std::endl; +// sleep(1); + if ((fabs(ecl::Maximum()(0.0, 2 * t, leading_quintics[j].derivative().derivative())) + < fabs(max_accelerations[j])) + && (fabs(ecl::Minimum()(0.0, 2 * t, leading_quintics[j].derivative().derivative())) + < fabs(max_accelerations[j]))) + { + if (j == dimension() - 1) + { // all joints are constrained, great! + leading_quintic_time = 2 * t; + // Everything done, force it to completely bail out of these loops. + quintic_constrained = true; + i = 5; + } + } + else + { // failed to constrain for this i value. + if (i == 5) + { // If we get here, even up to half the length of the segment has failed. + quintic_constrained = false; + } + break; + } + } + if (!quintic_constrained) + { // give up, go back to start of while loop with increased duration +// std::cout << "Quintic unconstrained, increasing the first duration : " << waypoints[0].duration() << std::endl; + waypoints[0].duration(waypoints[0].duration() * 1.1); // 10% increase + break; // from the for loop + } + } + } + + /****************************************** + ** Make the post pseudo point. + *******************************************/ + double trailing_quintic_time_0 = 0.0; + double trailing_quintic_time_f = 0.0; + quintic_constrained = false; + while (!quintic_constrained) + { + quintic_constrained = true; + tension_splines = generateTensionSplines(tension, leading_quintic_time / 2); + for (unsigned int i = 1; i <= 5; ++i) + { + double t = i * waypoints[n - 1].duration() / 10; + double t_f = tension_splines[0].domain().back(); + for (unsigned int j = 0; j < dimension(); ++j) + { + double y_dot = tension_splines[j].derivative(t_f - t); + double y = tension_splines[j](t_f - t); + double y_f = waypoints[n].angles()[j]; + double y_f_dot = waypoints[n].rates()[j]; + trailing_quintics[j] = QuinticPolynomial::Interpolation(t_f - t, y, y_dot, 0.0, t_f + t, y_f, y_f_dot, 0.0); + + /********************* + ** Debugging + **********************/ +// std::cout << "Post Pseudo Point" << std::endl; +// std::cout << " Domain: " << tension_splines[0].domain() << std::endl; +// std::cout << " y[" << i << "," << j << "] : " << y << std::endl; +// std::cout << " y_dot[" << i << "," << j << "] : " << ydot << std::endl; +// double accel_max = fabs( Maximum()(t_f-t,t_f+t,trailing_quintics[j].derivative().derivative())); +// if ( accel_max < fabs( Minimum()(t_f-t,t_f+t,trailing_quintics[j].derivative().derivative())) ) { +// accel_max = fabs( Minimum()(t_f-t,t_f+t,trailing_quintics[j].derivative().derivative())); +// } +// std::cout << " accel[" << i << "," << j << "] : " << accel_max << std::endl; +// sleep(1); + if ((fabs(Maximum()(t_f - t, t_f + t, trailing_quintics[j].derivative().derivative())) + < fabs(max_accelerations[j])) + && (fabs(Minimum()(t_f - t, t_f + t, trailing_quintics[j].derivative().derivative())) + < fabs(max_accelerations[j]))) + { + if (j == dimension() - 1) + { // all joints are constrained, great! + trailing_quintic_time_0 = tension_splines[j].domain().back() - t; + trailing_quintic_time_f = tension_splines[j].domain().back() + t; + // Everything done, force it to completely bail out of these loops. + quintic_constrained = true; + i = 5; + } + } + else + { // failed to constrain for this i value. + if (i == 5) + { // If we get here, even up to half the length of the segment has failed. + quintic_constrained = false; + } + break; + } + } + if (!quintic_constrained) + { // give up, go back to start of while loop with increased duration + waypoints[n - 1].duration(waypoints[n - 1].duration() * 1.1); // 10% increase + break; + } + } + } + + /********************* + ** Debugging + **********************/ +// std::cout << "Leading Quintic Time :" << leading_quintic_time << std::endl; +// std::cout << "Trailing Quintic Time:" << trailing_quintic_time_0 << " " << trailing_quintic_time_f << std::endl; + /****************************************** + ** Finalise + *******************************************/ + trajectory_duration = trailing_quintic_time_f; + for (unsigned int j = 0; j < dimension(); ++j) + { + spline_functions[j][0] = new SplineFunction(0.0, leading_quintic_time, leading_quintics[j]); + spline_functions[j][1] = new SplineFunction(leading_quintic_time, trailing_quintic_time_0, + tension_splines[j]); + spline_functions[j][2] = new SplineFunction(trailing_quintic_time_0, trailing_quintic_time_f, + trailing_quintics[j]); + } + (void) result; // for unused variable warnings, in case the asserts weren't triggered +} + +void Trajectory::linearSplineInterpolation() +{ + if (!validateWaypoints(2)) + { + throw StandardException(LOC, ConfigurationError, + "Not all the waypoint maximum rates have been specified correctly (must be > 0.0)."); + } + if (!initialiseWaypointDurations()) + { + throw StandardException(LOC, ConfigurationError, "A waypoint was configured with a zero duration."); + } + + /****************************************** + ** Reserve Spline Storage Space + *******************************************/ + clearSplines(); // Clean up any pre-existing definition. + for (unsigned int j = 0; j < dimension(); ++j) + { + spline_functions[j].resize(1, NULL); + } + Array splines(dimension()); + + /****************************************** + ** Generate Splines + *******************************************/ + bool splines_constrained = false; + int n = waypoints.size() - 1; + while (!splines_constrained) + { + try + { + splines = generateLinearSplines(); + splines_constrained = true; +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation success" << std::endl; +#endif + } + catch (DataException &e) + { + /********************* + ** Stretch Waypoints + **********************/ + if (e.data() <= 0) + { +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation failed trying to create pre-pseudo, stretching first segment" << std::endl; +#endif + waypoints[0].duration(waypoints[0].duration() * 1.1); // 10% increase to w_{0}-w_{1} duration + } + else if (e.data() == 1) + { // error at corner prepseudo-w0-w1 +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation failed, stretching at corner " << e.data() << std::endl; +#endif + waypoints[0].duration(waypoints[0].duration() * 1.1); // 10% increase to w_{0}-w_{1} duration + } + else if (e.data() >= n + 1) + { // error at corner w_{n-1}-w_{n}-postpseudo +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation failed, stretching at corner " << e.data() << std::endl; +#endif + waypoints[n - 1].duration(waypoints[n - 1].duration() * 1.1); // 10% increase to w_{n-1}-w_{n} duration + } + else if (e.data() >= n + 2) + { + // occurs when trying to create the post-pseudo point + waypoints[n - 1].duration(waypoints[n - 1].duration() * 1.1); // 10% increase to w_{n-1}-w_{n} duration +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation failed trying to create post-pseudo, stretching last segment" << std::endl; +#endif + } + else + { +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: spline generation failed, stretching at corner " << e.data() << std::endl; +#endif + waypoints[e.data() - 2].duration(waypoints[e.data() - 2].duration() * 1.05); // 5% increase on either side + waypoints[e.data() - 1].duration(waypoints[e.data() - 1].duration() * 1.05); // 5% increase on either side + } + } + } + + /****************************************** + ** Finalise + *******************************************/ + trajectory_duration = splines[0].domain().back() - splines[0].domain().front(); + for (unsigned int j = 0; j < dimension(); ++j) + { + spline_functions[j][0] = new SplineFunction(0.0, splines[j].domain().back(), splines[j]); + } +} + +/***************************************************************************** + ** Implementation [Trajectory][Access] + *****************************************************************************/ + +double Trajectory::operator ()(const unsigned int& joint, const double& time) + +{ + + double t_f = spline_functions[joint][spline_functions[joint].size() - 1]->domain()[1]; + ecl_assert_throw( ( time >= 0.0 ) && ( time <= t_f + 0.0001 ), StandardException(LOC,OutOfRangeError)); + unsigned int i; + for (i = 0; i < spline_functions[joint].size(); ++i) + { + if (time <= spline_functions[joint][i]->domain()[1]) + { + return (*(spline_functions[joint][i]))(time); + } + } + // Sometimes machine precision can kill off some of the inequality arguments above (like e^{-16} error). Fallback: + return (*(spline_functions[joint][spline_functions[joint].size() - 1]))(t_f); +} + +double Trajectory::derivative(const unsigned int& joint, const double& time) + +{ + + double t_f = spline_functions[joint][spline_functions[joint].size() - 1]->domain()[1]; + ecl_assert_throw( ( time >= 0.0 ) && ( time <= t_f + 0.0001 ), StandardException(LOC,OutOfRangeError)); + unsigned int i; + for (i = 0; i < spline_functions[joint].size(); ++i) + { + if (time <= spline_functions[joint][i]->domain()[1]) + { + return spline_functions[joint][i]->derivative(time); + break; + } + } + // Sometimes machine precision can kill off some of the inequality arguments above (like e^{-16} error). Fallback: + return spline_functions[joint][spline_functions[joint].size() - 1]->derivative(t_f); +} + +double Trajectory::dderivative(const unsigned int& joint, const double& time) + +{ + + double t_f = spline_functions[joint][spline_functions[joint].size() - 1]->domain()[1]; + ecl_assert_throw( ( time >= 0.0 ) && ( time <= t_f + 0.0001 ), StandardException(LOC,OutOfRangeError)); + unsigned int i; + for (i = 0; i < spline_functions[joint].size(); ++i) + { + if (time <= spline_functions[joint][i]->domain()[1]) + { + return spline_functions[joint][i]->dderivative(time); + break; + } + } + // Sometimes machine precision can kill off some of the inequality arguments above (like e^{-16} error). Fallback: + return spline_functions[joint][spline_functions[joint].size() - 1]->dderivative(t_f); +} + +/***************************************************************************** + ** Implementation [Trajectory][Private] + *****************************************************************************/ + +bool Trajectory::validateWaypoints(unsigned int min_no_waypoints) +{ + + unsigned int n = waypoints.size() - 1; // n = number of segments + if (n + 1 < min_no_waypoints) + { + return false; + } + + for (unsigned int i = 0; i < n; ++i) + { // Dont care about the last waypoint w_n + for (unsigned int j = 0; j < waypoints[i].nominalRates().size(); ++j) + { + if (waypoints[i].nominalRates()[j] <= 0.0) + { + return false; + } + } + } + return true; +} + +bool Trajectory::initialiseWaypointDurations() +{ + + unsigned int n = waypoints.size() - 1; // n = number of segments + + // Waypoint durations are often not configured and default to 0.0 + + // Here we check the nominal rates and angle differences to automatically guess a + // duration. If the checks are ok, and this is bigger than the configured + // waypoint duration, then replace the waypoint duration with this calculation. + for (unsigned int i = 0; i < n; ++i) + { // Dont need to worry about the w_n's duration. + double max_duration = 0.0; + for (unsigned int j = 0; j < dimension(); ++j) + { + double distance = fabs(waypoints[i + 1].angles()[j] - waypoints[i].angles()[j]); + if (waypoints[i].nominalRates()[j] != 0.0) + { + double segment_duration = distance / waypoints[i].nominalRates()[j]; // Time = Distance/Velocity + if (segment_duration > max_duration) + { + max_duration = segment_duration; + } + } + } + if (max_duration > waypoints[i].duration()) + { + waypoints[i].duration(max_duration); + } + if (waypoints[i].duration() == 0.0) + { + return false; + } + } + return true; +} + +void Trajectory::clearSplines() +{ + for (unsigned int joint = 0; joint < dimension(); ++joint) + { + for (unsigned int function = 0; function < spline_functions[joint].size(); ++function) + { + if (spline_functions[joint][function] != NULL) + { + delete spline_functions[joint][function]; + spline_functions[joint][function] = NULL; + } + } + spline_functions[joint].clear(); + } +} + +void Trajectory::updateDuration() +{ + double total_time = 0.0; +// std::cout << "Durations: "; + for (unsigned int i = 0; i < waypoints.size() - 1; ++i) + { + total_time += waypoints[i].duration(); +// std::cout << waypoints[i].duration() << " "; + } +// std::cout << std::endl; + trajectory_duration = total_time; +} + +Array Trajectory::generateLinearSplines() +{ + // n = number of segments + // n+1 = number of input waypoints + // n+3 = number of waypoints (inc. pre-post pseudo) + + // This is a bit different from the cubic as we don't use this in a combo interpolater. + Array splines(dimension()); + unsigned int n = waypoints.size() - 1; // n = number of segments + Array waypoint_times(n + 3), values(n + 3); // Including pre and post points + + /****************************************** + ** Check rates are set for head/tail + *******************************************/ + // Note that we may yet change values[1] and values[n+1] when fixing the pseudo points below + // Set them all to zero (default option, i.e. starting at rest). + if (!waypoints[0].rates_configured()) + { + waypoints[0].rates() = WayPoint::JointDataArray::Constant(waypoints[0].dimension(), 0.0); + } + if (!waypoints[n].rates_configured()) + { + waypoints[n].rates() = WayPoint::JointDataArray::Constant(waypoints[n].dimension(), 0.0); + } + + /****************************************** + ** Make the pre pseudo point. + *******************************************/ + /* + * Pull back the first waypoint, find intersection of initial tangent line and the nominal rate line. + * Why? This lets us ensure the first segment is of the specified velocity, and the second segment will + * fall the correct between nominal rates required to get to w_1. + * + * x_ + * ^ \__ + * / \ + * o ------ o + * / + * / + * x + * + * - diagonal lines : nominal rate slopes + * - x : possible pseudo waypoints (at intersection of initial velocity line and nominal rate line) + * + * Basic process: + * + * - pullback a bit + * - get intersections as above + * - find minimum time intersection time (t_first_duration) + * - synchronise a pseudo waypoint at that time on the initial tangents for each joint (only 1 of these will be an actual intersection point) + * - check acceleration constraints of quintics for this waypoint at each joint + * - if fail, pullback again, if success, done! + */ + std::vector initial_tangents; // these are the lines from potential pseudo point to w_1, our eventual pseudo point must lie on it. + std::vector initial_angles, initial_rates; + for (unsigned int j = 0; j < dimension(); ++j) + { + initial_angles.push_back(waypoints[0].angles()[j]); + initial_rates.push_back(waypoints[0].rates()[j]); + initial_tangents.push_back(LinearFunction::PointSlopeForm(0, initial_angles[j], initial_rates[j])); + } + std::vector > pseudo_points(dimension()); + std::vector nominal_rate_lines(dimension()); + WayPoint pre_pseudo_waypoint(dimension()); + double t_pullback = 0.001; // start with 1ms + double t_pullback_max_ = waypoints[0].duration(); + double t_pre_intersect_duration = 0.0; // duration from the pulled back wp0 to the intersection point + bool acceleration_constraint_broken = true; + while (acceleration_constraint_broken && (t_pullback <= t_pullback_max_)) + { + // establish t_pre_intersect_duration as the minimum time to the intersection of initial tangent + // and nominal rate line + t_pre_intersect_duration = t_pullback_max_ / 2; + for (unsigned int j = 0; j < dimension(); ++j) + { + LinearFunction nominal_rate_line = LinearFunction::PointSlopeForm( + t_pullback, initial_angles[j], -1 * ecl::psign(initial_rates[j]) * waypoints[0].nominalRates()[j]); + CartesianPoint2d pseudo_point = LinearFunction::Intersection(initial_tangents[j], nominal_rate_line); + if (pseudo_point.x() < t_pre_intersect_duration) + { + t_pre_intersect_duration = pseudo_point.x(); + } + nominal_rate_lines[j] = nominal_rate_line; + } + acceleration_constraint_broken = false; + for (unsigned int j = 0; j < dimension(); ++j) + { + CartesianPoint2d pseudo_point(t_pre_intersect_duration, initial_tangents[j](t_pre_intersect_duration)); + // from the pseudo way point to the next way point (wp1) + double pseudo_point_duration = t_pullback + waypoints[0].duration() - t_pre_intersect_duration; + // Will test 5 positions, which cover all of t_pre_intersect_duration + // and half of pseudo_point_duration + for (unsigned int i = 1; i <= 5; ++i) + { + double t_l = t_pre_intersect_duration - i * t_pre_intersect_duration / 5.0; + double t_r = t_pre_intersect_duration + i * pseudo_point_duration / 10.0; + LinearFunction segment = LinearFunction::Interpolation(pseudo_point.x(), pseudo_point.y(), + t_pullback + waypoints[0].duration(), + waypoints[1].angles()[j]); + double y_0 = initial_tangents[j](t_l); + double y_0_dot = initial_tangents[j].derivative(t_l); + double y = segment(t_r); + double y_dot = segment.derivative(t_r); // slope + QuinticPolynomial quintic = QuinticPolynomial::Interpolation(t_l, y_0, y_0_dot, 0.0, t_r, y, y_dot, 0.0); + if ((fabs(CubicPolynomial::Maximum(t_l, t_r, quintic.derivative().derivative())) < fabs(max_accelerations[j])) + && (fabs(CubicPolynomial::Minimum(t_l, t_r, quintic.derivative().derivative())) < fabs(max_accelerations[j]))) + { + acceleration_constraint_broken = false; + break; // we're good, get out and continue through all the joints + } + if (i == 5) + { +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: pre psuedo point failed with acceleration checks [" << t_pre_intersect_duration << "][" << t_pullback << "]" << std::endl; +#endif + acceleration_constraint_broken = true; + } + } + } + t_pullback = t_pullback * 2; // takes 11 runs to get from 1ms to 1s; adjust, if this is too much + } + if (acceleration_constraint_broken) + { + throw DataException(LOC, ConstructorError, "Max acceleration bound broken by pre pseudo point.", 0); + } + pre_pseudo_waypoint.duration(t_pullback + waypoints[0].duration() - t_pre_intersect_duration); + for (unsigned int j = 0; j < dimension(); ++j) + { + pre_pseudo_waypoint.angles()[j] = initial_tangents[j](t_pre_intersect_duration); + } +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: pre psuedo point done!" << std::endl; + std::cout << " : angles " << pre_pseudo_waypoint.angles() << std::endl; + std::cout << " : pre pseudo duration " << t_pre_intersect_duration << std::endl; + std::cout << " : modified first waypoint duration " << pre_pseudo_waypoint.duration() << std::endl; +#endif + + /****************************************** + ** Make the post pseudo point. + *******************************************/ + std::vector final_angles, final_rates; + for (unsigned int j = 0; j < dimension(); ++j) + { + final_angles.push_back(waypoints[n].angles()[j]); + final_rates.push_back(waypoints[n].rates()[j]); + nominal_rate_lines[j] = LinearFunction::PointSlopeForm( + 0, final_angles[j], -1 * ecl::psign(final_rates[j]) * waypoints[n - 1].nominalRates()[j]); + } + std::vector final_tangents(dimension()); + WayPoint post_pseudo_waypoint(dimension()); + double t_pullforward = 0.001; // start with 1ms + double t_pullforward_max_ = waypoints[n - 1].duration(); + double t_post_intersect_duration = 0.0; // duration from the pulled back wp0 to the intersection point + acceleration_constraint_broken = true; + while (acceleration_constraint_broken && (t_pullforward <= t_pullforward_max_)) + { + // establish t_final as the maximum time to the intersection of final tangent and nominal rate line + t_post_intersect_duration = 0.0; + for (unsigned int j = 0; j < dimension(); ++j) + { + LinearFunction final_tangent = LinearFunction::PointSlopeForm(t_pullforward, final_angles[j], final_rates[j]); + final_tangents[j] = final_tangent; + CartesianPoint2d pseudo_point = LinearFunction::Intersection(final_tangents[j], nominal_rate_lines[j]); + if (pseudo_point.x() > t_post_intersect_duration) + { + t_post_intersect_duration = pseudo_point.x(); + } + } + // check acceleration constraints + acceleration_constraint_broken = false; + for (unsigned int j = 0; j < dimension(); ++j) + { + CartesianPoint2d pseudo_point(t_post_intersect_duration, final_tangents[j](t_post_intersect_duration)); + double pseudo_point_duration = t_pullforward - t_post_intersect_duration; + for (unsigned int i = 1; i <= 5; ++i) + { + double t_l = t_post_intersect_duration - i * (waypoints[n - 1].duration() + t_post_intersect_duration) / 10.0; + double t_r = t_post_intersect_duration + i * pseudo_point_duration / 5.0; + LinearFunction segment = LinearFunction::Interpolation(-waypoints[n - 1].duration(), + waypoints[n - 1].angles()[j], pseudo_point.x(), + pseudo_point.y()); + double y_0 = segment(t_l); + double y_0_dot = segment.derivative(t_l); + double y = final_tangents[j](t_r); + double y_dot = final_tangents[j].derivative(t_r); + QuinticPolynomial quintic = QuinticPolynomial::Interpolation(t_l, y_0, y_0_dot, 0.0, t_r, y, y_dot, 0.0); + if ((fabs(CubicPolynomial::Maximum(t_l, t_r, quintic.derivative().derivative())) < fabs(max_accelerations[j])) + && (fabs(CubicPolynomial::Minimum(t_l, t_r, quintic.derivative().derivative())) < fabs(max_accelerations[j]))) + { + acceleration_constraint_broken = false; + break; // we're good, get out and continue through all the joints + } + if (i == 5) + { +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: post psuedo point failed with acceleration checks [" << t_post_intersect_duration << "][" << t_pullforward << "]" << std::endl; +#endif + acceleration_constraint_broken = true; + } + } + } + t_pullforward = t_pullforward * 2; // takes 12 runs to get from 1ms to 1s, adjust, if this is too much + } + if (acceleration_constraint_broken) + { + throw DataException(LOC, ConstructorError, "Max acceleration bound broken by pre pseudo point.", 0); + } + post_pseudo_waypoint.duration(t_pullforward - t_post_intersect_duration); + for (unsigned int j = 0; j < dimension(); ++j) + { + post_pseudo_waypoint.angles()[j] = final_tangents[j](t_post_intersect_duration); + } +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: post psuedo point done!" << std::endl; + std::cout << " : angles " << post_pseudo_waypoint.angles() << std::endl; + std::cout << " : modified last point duration " << waypoints[n-1].duration() + t_post_intersect_duration << std::endl; + std::cout << " : post pseudo duration " << post_pseudo_waypoint.duration() << std::endl; +#endif + + /********************* + ** Waypoint Times + **********************/ + // n+3 points (w_0...w_n + pre and post pseudos) + // n+3 waypoint_times + waypoint_times[0] = 0.0; + waypoint_times[1] = t_pre_intersect_duration; + waypoint_times[2] = t_pre_intersect_duration + pre_pseudo_waypoint.duration(); + for (unsigned int i = 2; i < n; ++i) + { + waypoint_times[i + 1] = waypoint_times[i] + waypoints[i - 1].duration(); + } + waypoint_times[n + 1] = waypoint_times[n] + waypoints[n - 1].duration() + t_post_intersect_duration; + waypoint_times[n + 2] = waypoint_times[n + 1] + post_pseudo_waypoint.duration(); + +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: waypoint time estimates before interpolation: " << waypoint_times << std::endl; +#endif + + for (unsigned int j = 0; j < dimension(); ++j) + { + /****************************************** + ** Set Values + *******************************************/ + values[0] = waypoints[0].angles()[j]; + values[1] = pre_pseudo_waypoint.angles()[j]; + for (unsigned int i = 2; i <= n; ++i) + { + values[i] = waypoints[i - 1].angles()[j]; + } + values[n + 1] = post_pseudo_waypoint.angles()[j]; + values[n + 2] = waypoints[n].angles()[j]; +#ifdef DEBUG_LINEAR_INTERPOLATION + std::cout << "Linear Interpolation: values[" << j << "]: " << values << std::endl; +#endif + + /****************************************** + ** Generate Spline + *******************************************/ + try + { + splines[j] = SmoothLinearSpline::Interpolation(waypoint_times, values, max_accelerations[j]); + } + catch (DataException &e) + { + throw DataException(LOC, e); + } + } +#ifdef DEBUG_LINEAR_INTERPOLATION + for ( unsigned int j = 0; j < dimension(); ++j) + { + std::cout << "Linear Interpolation: discretised domain [" << j << "]: " << splines[j].domain() << std::endl; + } +#endif + return splines; +} + +Array Trajectory::generateTensionSplines(const double& tension, const double initial_time) +{ + + Array tension_splines(dimension()); + unsigned int n = waypoints.size() - 1; // n = number of segments + // Include all waypoints (even w_0 and w_n). We set up pre and post pseudo points later. + Array waypoint_times(n + 1), values(n + 1); + waypoint_times[0] = initial_time; + for (unsigned int i = 1; i < n + 1; ++i) + { + waypoint_times[i] = waypoint_times[i - 1] + waypoints[i - 1].duration(); + } + + for (unsigned int j = 0; j < dimension(); ++j) + { + for (unsigned int i = 0; i < n + 1; ++i) + { + values[i] = waypoints[i].angles()[j]; + } + tension_splines[j] = TensionSpline::Natural(waypoint_times, values, tension); + } + return tension_splines; +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/waypoint.cpp b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/waypoint.cpp new file mode 100644 index 0000000..0c0d69e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/lib/waypoint.cpp @@ -0,0 +1,27 @@ +/** + * @file /ecl_manipulators/src/lib/waypoint.cpp + * + * @brief Implementation of joint angle waypoints. + * + * @date October 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/manipulators/waypoint.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/CMakeLists.txt new file mode 100644 index 0000000..dc47432 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/CMakeLists.txt @@ -0,0 +1,24 @@ +############################################################################### +# GTest setup +############################################################################### + +macro(ecl_add_manipulators_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} + ${PROJECT_NAME} + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_linear_algebra::ecl_linear_algebra + ecl_math::ecl_math + ) + endif() +endmacro(ecl_add_manipulators_gtest) + +############################################################################### +# GTests +############################################################################### + +ecl_add_manipulators_gtest(trajectories) +ecl_add_manipulators_gtest(waypoints) + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/test/trajectories.cpp b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/trajectories.cpp new file mode 100644 index 0000000..e0b4e6b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/trajectories.cpp @@ -0,0 +1,221 @@ +/** + * @file /src/test/trajectories.cpp + * + * @brief Unit Test for trajectories, results also get saved in a file. + * + * @date July, 1st, 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../include/ecl/manipulators/waypoint.hpp" +#include "../../include/ecl/manipulators/trajectory.hpp" + + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::cout; +using std::endl; +using std::string; +using ecl::Array; +using ecl::RightAlign; +using ecl::Format; +using ecl::CubicPolynomial; +using ecl::GenericSplineFunction; +using ecl::SplineFunction; +using ecl::JointAngles; +using ecl::Trajectory; +using ecl::WayPoint; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TrajectoryTests,allEggsInOneBasket) { + // Haven't got around to running this properly through gtests yet. + SUCCEED(); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + Format string_format; string_format.width(8); string_format.align(RightAlign); + Format format; format.width(8); format.precision(2); format.align(RightAlign); + int n = 200; + + std::ofstream tension_file_output, linear_file_output; + tension_file_output.open("tension_interpolation.dat"); + linear_file_output.open("linear_interpolation.dat"); + tension_file_output << "# Created by trajectories_output_to_file test." << endl; + tension_file_output << "# name: tension_interpolation" << endl; + tension_file_output << "# type: matrix" << endl; + tension_file_output << "# rows: " << (n + 1) * 3 << endl; + tension_file_output << "# columns: " << 1 + 2 * 3 << endl; + tension_file_output << endl; + linear_file_output << "# Created by trajectories_output_to_file test." << endl; + linear_file_output << "# name: linear_interpolation" << endl; + linear_file_output << "# type: matrix" << endl; + linear_file_output << "# rows: " << (n + 1) * 3 << endl; + linear_file_output << "# columns: " << 1 + 2 * 3 << endl; + linear_file_output << endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructor" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + Trajectory trajectory(2,"Crash Test Dummy"); + + /****************************************** + ** Common Waypoint Parameters + *******************************************/ + WayPoint initial_waypoint(2), waypoint(2), final_waypoint(2); + + initial_waypoint.name("Initial Position"); + initial_waypoint.angles() << 1.0, 1.0; + initial_waypoint.rates() << 0.0, 2.0; + initial_waypoint.nominalRates(0.5); + trajectory.append(initial_waypoint); + + waypoint.name("Second Waypoint"); + waypoint.angles() << 2.0, 0.0; + waypoint.nominalRates(1.0); + trajectory.append(waypoint); + + waypoint.name("Mid Waypoint"); + waypoint.angles() << 1.0, 5.0; + waypoint.nominalRates(1.2); + trajectory.append(waypoint); + + waypoint.name("Fourth Waypoint"); + waypoint.angles() << 3.0, 3.0; + waypoint.nominalRates(0.5); + trajectory.append(waypoint); + + final_waypoint.name("End Position"); + final_waypoint.angles() << 4.0, 2.0; + final_waypoint.nominalRates(0.5); + final_waypoint.rates() << 0.0, 1.0; + trajectory.append(final_waypoint); + + std::cout << trajectory << std::endl; + + trajectory.maxAccelerations(5); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Tension Spline Interpolation" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + trajectory.tensionSplineInterpolation(4.0); // Tension arg + +// cout << string_format("t "); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''"); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''"); +// cout << endl; + for ( int i = 0; i <= n; ++i ) { + double x; + if ( i != n ) { + x = i*(trajectory.duration())/n; + } else { + x = trajectory.duration(); + } +// cout << format(x); +// cout << format(trajectory(0,x)); +// cout << format(trajectory.derivative(0,x)); +// cout << format(trajectory.dderivative(0,x)); +// cout << format(trajectory(1,x)); +// cout << format(trajectory.derivative(1,x)); +// cout << format(trajectory.dderivative(1,x)); +// cout << endl; + + tension_file_output << format(x); + tension_file_output << format(trajectory(0,x)); + tension_file_output << format(trajectory.derivative(0,x)); + tension_file_output << format(trajectory.dderivative(0,x)); + tension_file_output << format(trajectory(1,x)); + tension_file_output << format(trajectory.derivative(1,x)); + tension_file_output << format(trajectory.dderivative(1,x)); + tension_file_output << endl; + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Smooth Linear Spline Interpolation" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + trajectory.maxAccelerations(5); + trajectory.linearSplineInterpolation(); + +// cout << string_format("t "); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''"); +// cout << string_format("y "); +// cout << string_format("y' "); +// cout << string_format("y''"); +// cout << endl; + for ( int i = 0; i <= n; ++i ) { + double x; + if ( i != n ) { + x = i*(trajectory.duration())/n; + } else { + x = trajectory.duration(); + } +// cout << format(x); +// cout << format(trajectory(0,x)); +// cout << format(trajectory.derivative(0,x)); +// cout << format(trajectory.dderivative(0,x)); +// cout << format(trajectory(1,x)); +// cout << format(trajectory.derivative(1,x)); +// cout << format(trajectory.dderivative(1,x)); +// cout << endl; + + linear_file_output << format(x); + linear_file_output << format(trajectory(0,x)); + linear_file_output << format(trajectory.derivative(0,x)); + linear_file_output << format(trajectory.dderivative(0,x)); + linear_file_output << format(trajectory(1,x)); + linear_file_output << format(trajectory.derivative(1,x)); + linear_file_output << format(trajectory.dderivative(1,x)); + linear_file_output << endl; + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + tension_file_output.close(); + linear_file_output.close(); + std::cout << "Trajectories written to files 'linear_interpolation.dat', 'tension_interpolation.dat'." << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_manipulators/src/test/waypoints.cpp b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/waypoints.cpp new file mode 100644 index 0000000..709987e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_manipulators/src/test/waypoints.cpp @@ -0,0 +1,69 @@ +/** + * @file /src/test/waypoints.cpp + * + * @brief Unit Test for manipulator waypoints. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/manipulators/waypoint.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Array; +using ecl::JointAngles; +using ecl::WayPoint; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(WayPointTests,allEggsInOneBasket) { + // Haven't got around to running this properly through gtests yet. + SUCCEED(); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructor" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Manual Construction: " << std::endl; + WayPoint waypoint2(4); + waypoint2.name("Raised Position"); + waypoint2.angles() << 1.57, 1.57, 0.00, 0.00; + waypoint2.rates() << 1.0, 1.0, 0.8, 0.8; + waypoint2.accelerations() << 0.9, 0.9, 0.6, 0.6; + waypoint2.nominalRates(1.0); + waypoint2.nominalRates() << 1.0, 1.0, 0.8, 0.8; + std::cout << waypoint2 << std::endl; + + std::cout << "Copy construction" << std::endl; + WayPoint waypoint3(waypoint2); + std::cout << waypoint3 << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_math/.cproject b/ros2_ws/src/ecl_core/ecl_math/.cproject new file mode 100644 index 0000000..f017d07 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/.cproject @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + tests + true + true + true + + + make + + clean + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_math/.project b/ros2_ws/src/ecl_core/ecl_math/.project new file mode 100644 index 0000000..a7db6a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/.project @@ -0,0 +1,78 @@ + + + ecl_math + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + tests + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_math/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_math/CHANGELOG.rst new file mode 100644 index 0000000..66450bf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/CHANGELOG.rst @@ -0,0 +1,7 @@ +========= +Changelog +========= + +0.61.12 (2016-05-03) +-------------------- +* negative sign function diff --git a/ros2_ws/src/ecl_core/ecl_math/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/CMakeLists.txt new file mode 100644 index 0000000..dce1995 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/CMakeLists.txt @@ -0,0 +1,65 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_math) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Project Configuration +############################################################################## + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_math/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_math/doxygen/mainpage.dox new file mode 100644 index 0000000..44b98fc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/doxygen/mainpage.dox @@ -0,0 +1,62 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This group includes various mathematical macros, constants and utility + functions/functors. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // constants + using ecl::pi; // also pi_2, pi_4 + + // simple functions + using ecl::EuclideanNorm; + using ecl::isApprox; + using ecl::isApproxOrLessThan; + using ecl::sign; // also psign + using ecl::cube_root; // only for real numbers/solutions + @endcode + + Since it is a collection of macros and headers only, no linking + is required if you are only utilising this functionality. + +\section usage Usage + + @subsection piSection Macros for PI + + Usually there will always be macros for pi defined in math.h, namely + M_PI, M_PI_2, etc... (sometimes they're unavailable, e.g. windoze!). + For typesafe definitions, the ecl defines a couple of these similarly in + the ecl::math namespace. + + @subsection functionsSection Simple Functions + + Various regularly used functions are also present - usually in the form + of functors (useful for passing around should it ever be necessary). + + - ecl::EuclideanNorm + - ecl::isApprox + - ecl::isApproxOrLessThan + +\section unitTests Unit Tests + + - /src/test/constants.cpp + - /src/test/fuzzy.cpp + - /src/test/norms.cpp + +\section ChangeLog + + - Dec 10 : fuzzy math. + - Sep 10 : better detection/setting of pi constants on posix/non-posix platforms. + - Feb 10 : @ref ecl::EuclideanNorm "Euclidean norm" functor (currently only l2 norm). + - May 09 : Macros for pi undefined and c++ style @ref ecl::pi "pi" constants made available. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_math/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_math/doxygen/namespaces.dox new file mode 100644 index 0000000..877b5a6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/doxygen/namespaces.dox @@ -0,0 +1,7 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_math/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..7c35137 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(math) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math.hpp b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math.hpp new file mode 100644 index 0000000..3aeca96 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math.hpp @@ -0,0 +1,24 @@ +/** + * @file /include/ecl/math.hpp + * + * @brief Family of mathematical macros, constants and functions. + * + * @date May, 2009. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MATH_HPP_ +#define ECL_MATH_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "math/constants.hpp" +#include "math/norms.hpp" +#include "math/fuzzy.hpp" +#include "math/simple.hpp" + +#endif /*ECL_MATH_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/CMakeLists.txt new file mode 100644 index 0000000..7c2d89d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/math) + diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/constants.hpp b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/constants.hpp new file mode 100644 index 0000000..5a518bd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/constants.hpp @@ -0,0 +1,60 @@ +/** + * @file /include/ecl/math/constants.hpp + * + * @brief Mathematical constants. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MATH_CONSTANTS_HPP_ +#define ECL_MATH_CONSTANTS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +#ifdef M_PI // defined by all POSIX systems and some non-POSIX ones + double const pi = M_PI; /**< @brief Mathematical constant for pi. */ + const double two_pi = 2.0*pi; /**< @brief Mathematical constant for 2*pi. */ + const double pi_2 = pi/2.0; /**< @brief Mathematical constant for pi/2. */ + const double pi_4 = pi/4.0; /**< @brief Mathematical constant for pi/4. */ + const float two_pi_f= two_pi; /**< @brief Mathematical constant (float format) for 2*pi. */ + const float pi_f = pi; /**< @brief Mathematical constant (float format) for pi. */ + const float pi_2_f = pi_2; /**< @brief Mathematical constant (float format) for pi/2. */ + const float pi_4_f = pi_4; /**< @brief Mathematical constant (float format) for pi/4. */ +#else + double const pi = 4.0*std::atan(1.0); /**< @brief Mathematical constant for pi. */ + const double two_pi = 2.0*pi; /**< @brief Mathematical constant for 2*pi. */ + const double pi_2 = pi/2.0; /**< @brief Mathematical constant for pi/2. */ + const double pi_4 = pi/4.0; /**< @brief Mathematical constant for pi/4. */ + const float two_pi_f= two_pi; /**< @brief Mathematical constant (float format) for 2*pi. */ + const float pi_f = pi; /**< @brief Mathematical constant (float format) for pi. */ + const float pi_2_f = pi_2; /**< @brief Mathematical constant (float format) for pi/2. */ + const float pi_4_f = pi_4; /**< @brief Mathematical constant (float format) for pi/4. */ +#endif + +// Above method of setting is more intelligent. +//const double two_pi = 6.283185307179586476925286766559005768394338798750211641949888; /**< @brief Mathematical constant for 2*pi. */ +//const double pi = 3.141592653589793238462643383279502884197169399375105820974944; /**< @brief Mathematical constant for pi. */ +//const double pi_2 = 1.57079632679489661923; /**< @brief Mathematical constant for pi/2. */ +//const double pi_4 = 0.78539816339744830962; /**< @brief Mathematical constant for pi/4. */ +//const float two_pi_f= 6.283185307179586476925286766559005768394338798750211641949888; /**< @brief Mathematical constant (float format) for 2*pi. */ +//const float pi_f = 3.141592653589793238462643383279502884197169399375105820974944; /**< @brief Mathematical constant (float format) for pi. */ +//const float pi_2_f = 1.57079632679489661923; /**< @brief Mathematical constant (float format) for pi/2. */ +//const float pi_4_f = 0.78539816339744830962; /**< @brief Mathematical constant (float format) for pi/4. */ + + +} // namespace ecl + +#endif /*ECL_MATH_CONSTANTS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/fuzzy.hpp b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/fuzzy.hpp new file mode 100644 index 0000000..0cdbd32 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/fuzzy.hpp @@ -0,0 +1,180 @@ +/** + * @file /ecl_math/include/ecl/math/fuzzy.hpp + * + * @brief Fuzzy math operators. + * + * Not really fuzzy math, but simple operators for when values are close to + * the real deal. This could probably use an epsilon-approximate operator as well. + * + * @date Dec 29, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MATH_FUZZY_HPP_ +#define ECL_MATH_FUZZY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +//#include "num_traits.hpp" +#include // floating point std::abs +#include // integral std::abs +#include // std::min, std::max +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +/** + * @cond DO_NOT_DOXYGEN + */ +namespace implementations { + +/**************************************************************************** +* Implementation of fuzzy comparisons * +****************************************************************************/ + +/** + * @brief Parent template for scalar fuzzy implementations. + * + * This class is fully realised in its specialisations. + */ +template +struct scalar_fuzzy_default_impl {}; + +/** + * @brief Fuzzy math implementation for floating points. + * + * @tparam Scalar : autoselected by numeric traits as always being integer. + */ +template +struct scalar_fuzzy_default_impl +{ + typedef typename ecl::numeric_limits::Precision Precision; + + template + static inline bool isApprox(const Scalar& x, const OtherScalar& y, const Precision& prec) { + // casting just in case y is an integer type. + return std::abs(x - static_cast(y)) <= std::min( std::abs(x), std::abs(static_cast(y))) * prec; + } + + template + static inline bool isApproxOrLessThan(const Scalar& x, const OtherScalar& y, const Precision& prec) { + return x <= y || isApprox(x, y, prec); + } +}; + +/** + * @brief Fuzzy math implementation for integers. + * + * @tparam Scalar : autoselected by numeric traits as always being integer. + */ +template +struct scalar_fuzzy_default_impl { + + typedef typename ecl::numeric_limits::Precision Precision; + + template + static inline bool isApprox(const Scalar& x, const OtherScalar& y, const Precision& prec) { + // this will trigger if default argument is used (dummy precision for integers == 0) + if ( ecl::numeric_limits::is_integer ) { + return x == y; + } else { + // only get here if its not complex, so OtherScalar has to be a floating type + typename ecl::numeric_limits::Precision precision; + if ( prec == 0.0 ) { + precision = ecl::numeric_limits::dummy_precision; + } else { + precision = static_cast(prec); + } + return std::abs(static_cast(x) - y) <= std::min( std::abs(static_cast(x)), std::abs(y)) * precision; + } + } + template + static inline bool isApproxOrLessThan(const Scalar& x, const OtherScalar& y, const Precision&) { + return x <= y; + } +}; + +///** +// * @brief Fuzzy math implementation for complex numbers. +// * +// * Specialisation of fuzzy math functions for complex numbers. +// * +// * @tparam Scalar : autoselected by numeric traits as always being complex. +// */ +//template +//struct scalar_fuzzy_default_impl { +// typedef typename ecl::NumTraits::Precision Precision; +// +// static inline bool isApprox(const Scalar& x, const Scalar& y, const Precision& prec) { +// return ei_abs2(x - y) <= std::min(ei_abs2(x), ei_abs2(y)) * prec * prec; +// } +//}; + +/** + * @brief Fuzzy implementation selector (using numeric traits). + * + * Chooses the correct implementation via use of the numeric traits class. + * + * @tparam Scalar : the type of number being used (floating, integer, complex). + */ +template +struct scalar_fuzzy_impl : implementations::scalar_fuzzy_default_impl::is_integer> {}; + +} // implementations + +/** + * @endcond + */ +/***************************************************************************** +** Direct Interfaces +*****************************************************************************/ + +/** + * @brief Checks if two values are approximate. + * + * Note that this does not use the usual direct epsilon bound check, + * instead, it uses the magnitudes of the values and supplied + * precision to determine the epsilon bounds before carrying out the + * operation. + * + * @param x - first input argument + * @param y - second input argument + * @param precision - precision to use (default is defined by the type). + * @return bool : true or false of the operation. + */ +template +inline bool isApprox(const Scalar& x, const OtherScalar& y, typename numeric_limits::Precision precision = numeric_limits::dummy_precision) { + return implementations::scalar_fuzzy_impl::isApprox(x, y, precision); +} + +/** + * @brief Checks if the first value is less than or approximate to the second. + * + * Note that this does not use the usual direct epsilon bound check, + * instead, it uses the magnitudes of the values and supplied + * precision to determine the epsilon bounds before carrying out the + * operation. + * + * @param x - first input argument + * @param y - second input argument + * @param precision - precision to use (default is defined by the type). + * @return bool : true or false of the operation. + */ +template +inline bool isApproxOrLessThan(const Scalar& x, const OtherScalar& y, typename numeric_limits::Precision precision = numeric_limits::dummy_precision) { + return implementations::scalar_fuzzy_impl::isApproxOrLessThan(x, y, precision); +} + + + +} // namespace ecl + +#endif /* ECL_MATH_FUZZY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/norms.hpp b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/norms.hpp new file mode 100644 index 0000000..6d5c514 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/norms.hpp @@ -0,0 +1,101 @@ +/** + * @file /include/ecl/math/norms.hpp + * + * @brief Some simple functors to calculate various norms. + * + * These aren't meant to be all encompassing, rather just a few oft used + * functions that always seem to crop up. Use eigen for more complicated + * functionalities. + * + * @date February 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MATH_NORMS_HPP_ +#define ECL_MATH_NORMS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Functors +*****************************************************************************/ +/** + * @brief Functor for euclidean norms. + * + * This class can calculate euclidean norms for any type (int, float, double). + */ +class EuclideanNorm { +public: + /** + * @brief Functor operator for euclidean norms of dimension 2. + * + * @param x1 : first argument + * @param x2 : second argument + * @return T : result of the input. + */ + template + T operator()(const T& x1, const T& x2) { + return std::sqrt(x1*x1 + x2*x2); + } + + /** + * @brief Functor operator for euclidean norms of dimension 3. + * + * @param x1 : first argument + * @param x2 : second argument + * @param x3 : third argument + * @return T : result of the input. + */ + template + T operator()(const T& x1, const T& x2, const T& x3) { + return std::sqrt(x1*x1 + x2*x2 + x3*x3); + } + + // n dimensional cases using vectors, valarrays and eigen vectors here. + + // maybe also a norm(vectorx, vectory) which is sqrt((x0-y0)^2+(x1-y1)^2.....) +}; + +/***************************************************************************** +** Functions +*****************************************************************************/ +/** + * @brief Function for euclidean norms of dimension 2. + * + * @param x1 : first argument + * @param x2 : second argument + * @return T : result of the input. + */ +template +T euclidean_norm(const T& x1, const T& x2) { + return std::sqrt(x1*x1 + x2*x2); +} + +/** + * @brief Function for euclidean norms of dimension 3. + * + * @param x1 : first argument + * @param x2 : second argument + * @param x3 : second argument + * @return T : result of the input. + */ +template +T euclidean_norm(const T& x1, const T& x2, const T& x3) { + return std::sqrt(x1*x1 + x2*x2 + x3*x3); +} + +} // namespace ecl + +#endif /* ECL_MATH_NORMS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/simple.hpp b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/simple.hpp new file mode 100644 index 0000000..3839bc0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/include/ecl/math/simple.hpp @@ -0,0 +1,105 @@ +/** + * @file /ecl_math/include/ecl/math/simple.hpp + * + * @brief Simple math functions. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CORE_MATH_SIMPLE_HPP_ +#define ECL_CORE_MATH_SIMPLE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Functions +*****************************************************************************/ +/** + * @brief A sign function for numerical values. + * + * Note that zero will return zero, positive numbers +1, and negative numbers -1. + * + * @param x : scalar to test. + * @tparam Scalar : some numerical quantity satisfying a comparison with >= 0 + * @return bool : true if x is >= 0. + */ +template +inline int sign(const Scalar &x) { + // ToDo: should probably check some numeric traits here + // Is this faster? (v > 0) - (v < 0); + // http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c + if ( x > 0 ) { + return 1; + } else if ( x < 0 ) { + return -1; + } else { + return 0; + } +} + +/** + * @brief A sign function for numerical values (positive return if arg is zero). + * + * Note that zero will return +1, positive numbers +1, and negative numbers -1. + * + * @param x : scalar to test. + * @tparam Scalar : some numerical quantity satisfying a comparison with >= 0 + * @return bool : true if x is >= 0. + */ +template +inline int psign(const Scalar &x) { + // ToDo: should probably check some numeric traits here + if ( x >= 0 ) { + return 1; + } else { + return -1; + } +} + +/** + * @brief A sign function for numerical values (negative return if arg is zero). + * + * Note that zero will return -1, positive numbers +1, and negative numbers -1. + * + * @param x : scalar to test. + * @tparam Scalar : some numerical quantity satisfying a comparison with >= 0 + * @return bool : true if x is >= 0. + */ +template +inline int nsign(const Scalar &x) { + // ToDo: should probably check some numeric traits here + if ( x > 0 ) { + return 1; + } else { + return -1; + } +} + +/** + * @brief The real solution to a cube root. + * + * @param x : scalar to test. + * @tparam Scalar : a real numerical value + * @return Scalar : real value solution to the cubic root + */ +template +inline Scalar cube_root(const Scalar &x) { + // ToDo: should probably check some numeric traits here + return psign(x)*pow(fabs(x),1.0/3.0); +} + + +} // namespace ecl + +#endif /* ECL_CORE_MATH_SIMPLE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_math/package.xml b/ros2_ws/src/ecl_core/ecl_math/package.xml new file mode 100644 index 0000000..9b74deb --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/package.xml @@ -0,0 +1,34 @@ + + + ecl_math + 1.2.1 + + This package provides simple support to cmath, filling in holes + or redefining in a c++ formulation where desirable. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_math + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_type_traits + + ecl_license + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_math/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/src/CMakeLists.txt new file mode 100644 index 0000000..8750f10 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/CMakeLists.txt @@ -0,0 +1,9 @@ +############################################################################### +# Subdirectories +############################################################################### + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_math/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_math/src/test/CMakeLists.txt new file mode 100644 index 0000000..69e203b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/test/CMakeLists.txt @@ -0,0 +1,20 @@ +############################################################################### +# Macros +############################################################################### + +macro(ecl_math_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ecl_type_traits::ecl_type_traits) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_math_add_gtest(constants) +ecl_math_add_gtest(fuzzy) +ecl_math_add_gtest(norms) +ecl_math_add_gtest(simple) + diff --git a/ros2_ws/src/ecl_core/ecl_math/src/test/constants.cpp b/ros2_ws/src/ecl_core/ecl_math/src/test/constants.cpp new file mode 100644 index 0000000..f2552f8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/test/constants.cpp @@ -0,0 +1,36 @@ +/** + * @file /src/test/constants.cpp + * + * @brief Unit Test for the mathematical constants. + * + * @date May 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/math/constants.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(MathTests,pi) { + EXPECT_EQ(3.141592653589793238462643383279502884197169399375105820974944, ecl::pi); + EXPECT_EQ(1.57079632679489661923,ecl::pi_2); + EXPECT_EQ(0.78539816339744830962,ecl::pi_4); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_math/src/test/fuzzy.cpp b/ros2_ws/src/ecl_core/ecl_math/src/test/fuzzy.cpp new file mode 100644 index 0000000..9642a61 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/test/fuzzy.cpp @@ -0,0 +1,48 @@ +/** + * @file /ecl_math/src/test/fuzzy.cpp + * + * @brief Tests the fuzzy math implementations. + * + * @date Dec 30, 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/math/fuzzy.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(FuzzyTests,isApprox) { + EXPECT_TRUE(ecl::isApprox(3.0,3.0000000000000001)); + EXPECT_FALSE(ecl::isApprox(3.0,3.1000000000000001)); + EXPECT_TRUE(ecl::isApprox(3,3.0000000000000001)); + EXPECT_FALSE(ecl::isApprox(3,3.1000000000000001)); + EXPECT_TRUE(ecl::isApprox(3.0000000000000001,3)); + EXPECT_FALSE(ecl::isApprox(3.1000000000000001,3)); +} + +TEST(FuzzyTests,isApproxOrLessThan) { + EXPECT_TRUE(ecl::isApproxOrLessThan(3.0,3.0000000000000001)); + EXPECT_TRUE(ecl::isApproxOrLessThan(2.0,3.0000000000000001)); + EXPECT_FALSE(ecl::isApproxOrLessThan(4.0,3.0000000000000001)); + EXPECT_TRUE(ecl::isApproxOrLessThan(3,3.0000000000000001)); + EXPECT_TRUE(ecl::isApproxOrLessThan(2,3.0000000000000001)); + EXPECT_FALSE(ecl::isApproxOrLessThan(4,3.0000000000000001)); + EXPECT_TRUE(ecl::isApproxOrLessThan(3.0000000000000001,3)); + EXPECT_FALSE(ecl::isApproxOrLessThan(3.0000000000000001,2)); + EXPECT_TRUE(ecl::isApproxOrLessThan(3.0000000000000001,4)); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_math/src/test/norms.cpp b/ros2_ws/src/ecl_core/ecl_math/src/test/norms.cpp new file mode 100644 index 0000000..d4e987f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/test/norms.cpp @@ -0,0 +1,67 @@ +/** + * @file /src/test/norms.cpp + * + * @brief Unit Test for the norms. + * + * @date April 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/math/norms.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::EuclideanNorm; +using ecl::euclidean_norm; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(NormTests,euclideanNorm) { + EXPECT_EQ(5,EuclideanNorm()(3,4)); +} + +TEST(NormTests,euclideanNormFloats) { + float x = 3.0; + float y = 4.0; + float z = 5.0; + EXPECT_EQ(z,EuclideanNorm()(x,y)); +} + +TEST(NormTests,euclideanNormDoubles) { + double x = 3.0; + double y = 4.0; + double z = 5.0; + EXPECT_EQ(z,EuclideanNorm()(x,y)); +} + +TEST(NormTests,euclideanNormFunctions) { + double x = 3.0; + double y = 4.0; + double z = 5.0; + EXPECT_EQ(z,euclidean_norm(x,y)); + float xf = 3.0; + float yf = 4.0; + float zf = 5.0; + EXPECT_EQ(zf,euclidean_norm(xf,yf)); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + std::cout << "Numeric Limits: " << std::numeric_limits::min() << std::endl; + std::cout << "Numeric Limits: " << std::numeric_limits::max() << std::endl; + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_math/src/test/simple.cpp b/ros2_ws/src/ecl_core/ecl_math/src/test/simple.cpp new file mode 100644 index 0000000..9fb71e4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_math/src/test/simple.cpp @@ -0,0 +1,46 @@ +/** + * @file /ecl_math/src/test/simple.cpp + * + * @brief Tests the simple math implementations. + * + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/math/simple.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SimpleFunctionTests,sign) { + EXPECT_EQ(ecl::sign(3),1); + EXPECT_EQ(ecl::sign(0),0); + EXPECT_EQ(ecl::sign(-2),-1); + EXPECT_EQ(ecl::sign(3.3),1); + EXPECT_EQ(ecl::sign(0.0),0); + EXPECT_EQ(ecl::sign(-2.0),-1); + EXPECT_EQ(ecl::psign(3),1); + EXPECT_EQ(ecl::psign(0),1); + EXPECT_EQ(ecl::psign(-2),-1); + EXPECT_EQ(ecl::psign(3.3),1); + EXPECT_EQ(ecl::psign(0.0),1); + EXPECT_EQ(ecl::psign(-2.0),-1); +} + +TEST(SimpleFunctionTests,cube_root) { + EXPECT_FLOAT_EQ(2.0,ecl::cube_root(8.0)); + EXPECT_FLOAT_EQ(-2.0,ecl::cube_root(-8.0)); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/.cproject b/ros2_ws/src/ecl_core/ecl_mobile_robot/.cproject new file mode 100644 index 0000000..50fbc27 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/.cproject @@ -0,0 +1,658 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + + true + + true + + true + + + + + + make + + + + tests + + true + + true + + true + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/.project b/ros2_ws/src/ecl_core/ecl_mobile_robot/.project new file mode 100644 index 0000000..e6e8f64 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/.project @@ -0,0 +1,78 @@ + + + ecl_mobile_robot + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/CMakeLists.txt new file mode 100644 index 0000000..fc9986a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/CMakeLists.txt @@ -0,0 +1,62 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_mobile_robot) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_formatters REQUIRED) +find_package(ecl_geometry REQUIRED) +find_package(ecl_linear_algebra REQUIRED) +find_package(ecl_math REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_errors + ecl_formatters + ecl_geometry + ecl_linear_algebra + ecl_math +) +ament_package() + + + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/mainpage.dox new file mode 100644 index 0000000..1fa5c2c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/mainpage.dox @@ -0,0 +1,69 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Various representations and transforms relevant to mobile robot + platforms. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The error interfaces + using ecl::Pose; + using ecl::DifferentialDrive; + @endcode + + You will also need to link to -lecl_mobile_robot. + +\section usage Usage + + @subsection Pose + + This is the classical definition for a mobile robot's state in + a 2D world - [ x, y, heading ]. + + This class provides a convenient c++ container style interface + as well as a few mathematical operators for calculating + relative poses (differentials). + + @code + Pose pose1, pose2; + pose1 << 0,0,Math::pi/2; // comma initialisation + std::cout << pose.x() << pose.y() << pose.heading(); // readable access + std::cout << pose[0] << pose[1] << pose[1]; // vector style access + Pose pose3 = pose1 + pose2; // pose + relative pose + pose1 += pose2; // pose1 + relative pose + pose3 = pose1 - pose2; // calculates pose2 rel pose1 + @endcode + + + @subsection DifferentialDrive + + Currently there is only the diff drive kinematics class. This + provides functions for forward and inverse kinematics on a + differential drive type robot. + + @code + DifferentialDrive::Kinematics kinematics(0.1,0.5,0.05); // fixed axis length, centre offset, wheel radius + Pose dpose = kinematics.forward(0.2, 0.1); // left and right wheel angle updates -> differential pose + Vector2d wheel_vels = kinematics.inverse(0.1, 0.05); // linear/angular velocites -> left/right wheel angular rates + Vector2d vels = Kinematics::Inverse(pose1,pose2); // orig and final pose -> linear/angular platform velocities + @endcode + +\section unitTests Unit Tests & Sample Code + + - src/sample/pose.cpp + +\section ChangeLog + + - May 10 : extended and fully road-tested pose and differential drive interfaces. + - Jan 10 : added transforms used by the iclebo mobile platform (diff drive). + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/namespaces.dox new file mode 100644 index 0000000..b66aa9b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/doxygen/namespaces.dox @@ -0,0 +1,16 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::mobile_robot + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..5bf9599 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(mobile_robot) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot.hpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot.hpp new file mode 100644 index 0000000..35659df --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot.hpp @@ -0,0 +1,22 @@ +/** + * @file /include/ecl/mobile_robot.hpp + * + * @brief Mobile robot classes and algorithms. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MOBILE_ROBOT_HPP_ +#define ECL_MOBILE_ROBOT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "mobile_robot/differential_drive.hpp" + + +#endif /* ECL_MOBILE_ROBOT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/CMakeLists.txt new file mode 100644 index 0000000..6b20d0b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(kinematics) + +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/mobile_robot) + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/differential_drive.hpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/differential_drive.hpp new file mode 100644 index 0000000..4608aef --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/differential_drive.hpp @@ -0,0 +1,45 @@ +/** + * @file /ecl_mobile_robot/include/ecl/mobile_robot/differential_drive.hpp + * + * @brief Kinematics equations for differential drive type bases. + * + * @date 20/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_HPP_ +#define ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "kinematics/differential_drive.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface +*****************************************************************************/ + +/** + * @brief Differential drive properties and algorithms. + * + * This class typedefs various algorithm groups as well as providing + * some generic structures/methods for differential drive robot types. + */ +class ecl_mobile_robot_PUBLIC DifferentialDrive { +public: + typedef mobile_robot::DifferentialDriveKinematics Kinematics; +}; + +} // namespace ecl + +#endif /* ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/CMakeLists.txt new file mode 100644 index 0000000..69cad24 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/mobile_robot/kinematics) + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/differential_drive.hpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/differential_drive.hpp new file mode 100644 index 0000000..4dba299 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/kinematics/differential_drive.hpp @@ -0,0 +1,177 @@ +/** + * @file /ecl_mobile_robot/include/ecl/mobile_robot/kinematics/differential_drive.hpp + * + * @brief Kinematics equations for differential drive type bases. + * + * @date 20/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_KINEMATICS_HPP_ +#define ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_KINEMATICS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +namespace mobile_robot { + +/***************************************************************************** +** Interface +*****************************************************************************/ + +/** + * @brief Differential drive kinematics. + * + * This presents some of the differential drive kinematics transforms + * for a standard differential drive mobile base. The general structure is + * for a fixed axis between two separately controlled wheels, usually + * you can find a balancing castor wheel of some sort to the front or rear. + * + * @code + * + * o + * | + * | + * ||-------|| + * + * @endcode + * + * There are three sets of systems used to describe the + * kinematics. + * + * - /dot{theta}_L, /dot{theta}_R : wheel angular velocities. + * - /dot{s}, /omega : base linear speed and angular rotational velocities. + * - /dot{x}, /dot{y}, /dot{phi} : pose velocities wrt global frame. + * + * For all of these conversions, it is assumed the forward direction is the + * x axis for the local pose frame of reference and the frame of reference + * is located centrally between the two wheels. + */ +class ecl_mobile_robot_PUBLIC DifferentialDriveKinematics { +public: + /** + * @brief Configures the parameters defining the structure. + * + * @param fixed_axis_length : length between the two wheels [m]. + * @param wheel_radius : radius of each differential drive wheel [m]. + */ + DifferentialDriveKinematics( + const double& fixed_axis_length, + const double& wheel_radius) : + bias(fixed_axis_length), + radius(wheel_radius) + {} + + /** + * @brief Generates a relative (to the robot's frame) pose differential. + * + * Uses the odometry updates to generate a relative pose (x, y, heading) update. + * This differential can be used to update the current pose estimate. + * + * @code + * ecl::linear_algebra::Vector3d current_pose; + * // ... + * ecl::extend_pose(current_pose, poseUpdateFromWheelDifferential(0.1,0.2); + * @endcode + * + * @param dleft : incoming left wheel angle change. + * @param dright : incoming right wheel angle change. + * @return ecl::linear_algebra::Vector3d: pose update (differential - dx, dy, dheading). + */ + ecl::linear_algebra::Vector3d poseUpdateFromWheelDifferential( + const double& dleft, + const double &dright + ) const; + + /** + * @brief Generates a relative (to the robot's frame) pose differential. + * + * Use base translation and rotational differentials to generate a relative + * pose (x, y, heading) update. This differential can be used to update the + * current pose estimate. + * + * @code + * ecl::linear_algebra::Vector3d current_pose; + * // ... + * double translation = ....; + * double rotation = ..../ + * ecl::extend_pose( + * current_pose, + * poseUpdateFromBaseDifferential(translation, rotation); + * + * @param linearVelocity : incoming linear velocity of platform + * @param angularVelocity : incoming angular velocity of platform + * @return ecl::linear_algebra::Vector3d : pose update (differential) - dx, dy, dheading + */ + ecl::linear_algebra::Vector3d poseUpdateFromBaseDifferential( + const double& translation, + const double& rotation + ) const; + + /** + * @brief Generates wheel angle rates from scalar linear/angular velocity commands. + * + * Accepts the usual differential drive separation of linear and angular + * velocity components and computes the required wheel angle rates for control. + * + * @param linear_velocity : linear translation control command (in direction of facing). + * @param angular_velocity : angular rotation control command (around robot centre). + * @return Vector2d : left and right wheel angular rate commands respectively. + */ + ecl::linear_algebra::Vector2d baseToWheelVelocities( + const double& linear_velocity, + const double& angular_velocity + ) const; + + /** + * @brief Approximate conversion from [dx, dy, dtheta] -> [ds, dw]. + * + * The aim here is to provide a differential between two poses + * crudely approximated for non-holonomic motion by ds (linear translation) + * and dw (angular rotation). + * + * For any finite difference, this is in approximate, but one that + * approaches truth as the limit goes to zero. Consequently, so long + * as the step is small, the following is a reasonably simple, lightweight + * method. + * + * The ds is simply the scalar distance between two poses, given a sign + * for the direction it is pointing in (relative to the robot facing). Alternatively + * you could assume an angle + linear translation + angle or some such, but + * even then, its still an approximation. + * + * The angular difference, dw is more simple, it is always just the + * angular difference between poses. + * + * Jae-Yeong was talking about moving this to firmware for better accuracy + * (smaller update periods). + * + * @param a : initial pose + * @param b : final pose + * @return Vector2d : the differential [ds, dw]. + */ + static ecl::linear_algebra::Vector2d PoseToBaseDifferential( + const ecl::linear_algebra::Vector3d &a, + const ecl::linear_algebra::Vector3d &b + ); +private: + double bias, radius; +}; + +} // namespace mobile_robot +} // namespace ecl + +#endif /* ECL_MOBILE_ROBOT_DIFFERENTIAL_DRIVE_KINEMATICS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/macros.hpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/macros.hpp new file mode 100644 index 0000000..a6ec629 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/include/ecl/mobile_robot/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/mobile_robot/macros.hpp + * + * @brief Macros for ecl mobile robot. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MOBILE_ROBOT_MACROS_HPP_ +#define ECL_MOBILE_ROBOT_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_mobile_robot_EXPORTS // we are building a shared lib/dll + #define ecl_mobile_robot_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_mobile_robot_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_mobile_robot_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_mobile_robot_PUBLIC + #define ecl_mobile_robot_LOCAL +#endif + +#endif /* ECL_DEVICES_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/package.xml b/ros2_ws/src/ecl_core/ecl_mobile_robot/package.xml new file mode 100644 index 0000000..3069bcd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/package.xml @@ -0,0 +1,44 @@ + + + ecl_mobile_robot + 1.2.1 + + Contains transforms (e.g. differential drive inverse kinematics) + for the various types of mobile robot platforms. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_mobile_robot + https://github.com/stonier/ecl_navigation + https://github.com/stonier/ecl_navigation/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_build + ecl_license + ecl_errors + ecl_geometry + ecl_math + ecl_formatters + ecl_linear_algebra + + ecl_build + ecl_license + ecl_errors + ecl_geometry + ecl_math + ecl_formatters + ecl_linear_algebra + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/CMakeLists.txt new file mode 100644 index 0000000..25de5da --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/CMakeLists.txt @@ -0,0 +1,10 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(lib) +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/CMakeLists.txt new file mode 100644 index 0000000..a80bae2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/CMakeLists.txt @@ -0,0 +1,38 @@ +############################################################################### +# SOURCES +############################################################################### + +file(GLOB_RECURSE SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Install +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries(${PROJECT_NAME} + ecl_errors::ecl_errors + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_linear_algebra::ecl_linear_algebra + ecl_math::ecl_math +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/differential_drive.cpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/differential_drive.cpp new file mode 100644 index 0000000..77d4fb9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/lib/differential_drive.cpp @@ -0,0 +1,89 @@ +/** + * @file /ecl_mobile_robot/src/lib/kinematics/differential_drive.cpp + * + * @brief Implementation of the differential drive class. + * + * @date May 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/mobile_robot/kinematics/differential_drive.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace mobile_robot { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Angle; +using ecl::linear_algebra::Vector2d; +using ecl::linear_algebra::Vector3d; +using ecl::linear_algebra::Rotation2D; + +/***************************************************************************** +** Implementation [Kinematics] +*****************************************************************************/ + +ecl::linear_algebra::Vector3d DifferentialDriveKinematics::poseUpdateFromWheelDifferential(const double &dleft, const double& dright) const { + + double ds = radius*(dleft+dright)/2.0; + double domega = radius*(dright-dleft)/bias; + // Local robot frame of reference has the x axis pointing forward + // Since the pose update is using the robot frame of reference, the y update is zero + ecl::linear_algebra::Vector3d pose_update; + pose_update << ds, 0, ecl::wrap_angle(domega); + return pose_update; +} + +ecl::linear_algebra::Vector3d DifferentialDriveKinematics::poseUpdateFromBaseDifferential( + const double & translation, + const double & rotation +) const { + // Local robot frame of reference has the x axis pointing forward + // Since the pose update is using the robot frame of reference, the y update is zero + ecl::linear_algebra::Vector3d pose_update; + pose_update << translation, 0, ecl::wrap_angle(rotation); + return pose_update; +} + +Vector2d DifferentialDriveKinematics::baseToWheelVelocities(const double &linear_velocity, const double &angular_velocity) const { +// radius*(theta_dot_l+theta_dot_r)/2.0 = linear_velocity +// radius*(theta_dot_r-theta_dot_l)/bias = angular_velocity + Vector2d rates; + double right = (2*linear_velocity+angular_velocity*bias)/(2*radius); + double left = 2*linear_velocity/radius - right; + rates << left, right; + return rates; +} + +Vector2d DifferentialDriveKinematics::PoseToBaseDifferential( + const ecl::linear_algebra::Vector3d &a, + const ecl::linear_algebra::Vector3d &b) +{ + Vector2d diff; + diff << b[0] - a[0], b[1] - a[1]; + // This rotation doesn't affect the magnitude of ds, + // but it so the sign can work out properly + Vector2d dr = ecl::Angle(a[2]).rotationMatrix().inverse()*diff; + double ds = sqrt(dr(0)*dr(0)+dr(1)*dr(1)); + if ( dr(0) < 0.0 ) { + ds = -ds; + } + double dtheta = b[2] - a[2]; // difference in headings + ecl::wrap_angle(dtheta); + + return (diff << ds, dtheta).finished(); +} + +} // namespace mobile_robot +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/CMakeLists.txt new file mode 100644 index 0000000..dbad309 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/CMakeLists.txt @@ -0,0 +1,23 @@ +############################################################################### +# GTest setup +############################################################################### + +macro(ecl_add_mobile_robot_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} + ${PROJECT_NAME} + ecl_formatters::ecl_formatters + ecl_geometry::ecl_geometry + ecl_linear_algebra::ecl_linear_algebra + ecl_math::ecl_math + ) + endif() +endmacro(ecl_add_mobile_robot_gtest) + +############################################################################### +# GTests +############################################################################### + +ecl_add_mobile_robot_gtest(partial_inverse) + diff --git a/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/partial_inverse.cpp b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/partial_inverse.cpp new file mode 100644 index 0000000..dae0734 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mobile_robot/src/test/partial_inverse.cpp @@ -0,0 +1,51 @@ +/** + * @file /src/test/grid_map.cpp + * + * @brief Test the old inverse was the same as the new partial inverse function. + * + * @date October 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/mobile_robot/differential_drive.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(DifferentialDriveTests,allEggsInOneBasket) { + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Pose to Base Differential" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::linear_algebra::Vector3d a; a << 1.0, 2.0, ecl::pi/2.0; + ecl::linear_algebra::Vector3d b; b << 2.0, 3.0, ecl::pi; + + ecl::linear_algebra::Vector2d base_differential; + base_differential = ecl::DifferentialDrive::Kinematics::PoseToBaseDifferential(a, b); + + std::cout << "Base Differential: " << base_differential.transpose() << std::endl; + std::cout << std::endl; + + float abs_error = 0.01; + EXPECT_NEAR(std::sqrt(2.0), base_differential[0], abs_error); + EXPECT_NEAR(ecl::pi/2.0, base_differential[1], abs_error); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/.cproject b/ros2_ws/src/ecl_core/ecl_mpl/.cproject new file mode 100644 index 0000000..2dbe4bc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/.cproject @@ -0,0 +1,310 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/.project b/ros2_ws/src/ecl_core/ecl_mpl/.project new file mode 100644 index 0000000..51f97bd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/.project @@ -0,0 +1,82 @@ + + + ecl_mpl + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?children? + ?name?=outputEntries\|?children?=?name?=entry\\\\\\\|\\\|\|| + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_mpl/CHANGELOG.rst new file mode 100644 index 0000000..c1017d3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/CHANGELOG.rst @@ -0,0 +1,12 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_mpl +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.60.8 (2014-02-10) +------------------- + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_mpl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/CMakeLists.txt new file mode 100644 index 0000000..eda1817 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/CMakeLists.txt @@ -0,0 +1,57 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_mpl) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_mpl/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_mpl/doxygen/mainpage.dox new file mode 100644 index 0000000..afb94f8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/doxygen/mainpage.dox @@ -0,0 +1,128 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + +At this point, this package only provides very elementary support to the +other ecl template classes. Alot of ideas for these elements come from +both boost and the book "C++ Template Metaprogramming" by D.Abrahams. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit: + +@code +#include + +// The concept definition/validation classes. +using ecl::Bool; // compile time logic testing of template parameters +using ecl::enable_if; // selective specialisation of classes via the template parameters +using ecl::Unsigned; // type converters +@endcode + +Since it is a collection of template classes, no linking is required. + +\section Usage + +\subsection Bool + +Often used in the is_such_and_such_class traits testing classes. For example: + +@code +#include + +// Parent template which defaults to false +template +class is_foo_bar : public ecl::False {}; + +// Specialisations (in this case, class Tango) for which it is true +template <> +class is_foo_bar< Tango > : public ecl::True {}; + +// A class that will use it +template +class Cash { + static void says() { + std::cout << "Cash is fine." << std::endl; + } +}; + +// specialisation of that class for true +template <> +class Cash { + static void says() { + std::cout << "Cash is foobar too." << std::endl; + } +}; + +int main() { + Cash::value>::says(); // Cash is foobar too... + return 0; +} +@endcode + +\subsection enableIf Enable If + +These allow you to various compile tricks with SFINAE (Substitution Failure Is Not An Error). +One usage case is to specialise a template class for a whole group of classes that register +with a common type trait. + +@code +// This will instantiate if it is anything except float or double. +template +class TestObject { +public: + bool isFloatSpecialisation() { return false; } +}; + +// This specialisation will instantiate it T is float or double. +template +class TestObject< T, typename enable_if< is_float >::type > { +public: + bool isFloatSpecialisation() { return true; } +}; +@endcode + +\subsection failedObject Failed Object + +Simple class that guarantees a compile time failure if an attempt to instantiate it is made +(private constructor). Commonly you would use with the mpl if function. + +For example, the parent template definition above could be instead: + +@code +#include + +template +class TestObject : public ecl::FailedObject {}; +@endcode + + +\subsection converters Compile Time Converters + +Convert from one type to another in compile time. + +@code +char c = 0x33; +Unsigned::type uc = 0x03; +@endcode + +That example is trivial, but is more useful when using it for template arguments in a class. + +@code +template +class Foo { +private: + Unsigned::type my_unsigned_variable; +}; +@endcode + +@section ChangeLog + +- Feb 10 : moved out type traits to their own package. +- Aug 10 : @ref ecl::FailedObject "FailedObject" to throw compile time failures when metaprogramming. +- Jul 10 : @ref ecl::enable_if "enable_if" added until c++0x standards become mainstream. +- Jul 09 : @ref ecl::Bool "Bool", @ref ecl::if_c "If" constructs added. + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_mpl/doxygen/namespaces.dox new file mode 100644 index 0000000..745186e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/doxygen/namespaces.dox @@ -0,0 +1,7 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..4567f43 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(mpl) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl.hpp new file mode 100644 index 0000000..f276a90 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl.hpp @@ -0,0 +1,25 @@ +/** + * @file /include/ecl/mpl.hpp + * + * @brief Metaprogramming (pseudo) library. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_HPP_ +#define ECL_MPL_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "mpl/bool.hpp" +#include "mpl/if.hpp" +#include "mpl/enable_if.hpp" +#include "mpl/failed_object.hpp" +#include "mpl/converters.hpp" + +#endif /* ECL_MPL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/CMakeLists.txt new file mode 100644 index 0000000..efeb2f8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/mpl) + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/bool.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/bool.hpp new file mode 100644 index 0000000..7db1310 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/bool.hpp @@ -0,0 +1,46 @@ +/** + * @file /include/ecl/mpl/bool.hpp + * + * @brief Defines the metaprogamming equivalent of the boolean type. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_BOOL_HPP_ +#define ECL_MPL_BOOL_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +/** + * @brief Integral constant wrapper for boolean values. + * + * Provides an integral constant wrapper for boolean values (refer to C++ + * template metaprogramming by D.Abrahams p. 61 for details). + */ +template < bool x > +class Bool { +public: + static bool const value = x; /**< @brief The value for this integral constant wrapper. **/ + typedef Bool type; /**< @brief This wrapper's nullary metafunction (simply returns itself). **/ + typedef bool value_type; /**< @brief The type this wrapper's value. **/ + operator bool() const { return x; } /**< @brief Convenience conversion. **/ + virtual ~Bool(){}; +}; + +typedef Bool False; /**< @brief Convenient typedef for the 'false' integral constant wrapper. **/ +typedef Bool True; /**< @brief Convenient typedef for the 'true' integral constant wrapper. **/ + +} // namespace ecl + +#endif /* ECL_MPL_BOOL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/converters.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/converters.hpp new file mode 100644 index 0000000..9cf82c9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/converters.hpp @@ -0,0 +1,52 @@ +/** + * @file /ecl_mpl/include/ecl/mpl/converters.hpp + * + * @brief Type converters. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_CONVERTERS_HPP_ +#define ECL_MPL_CONVERTERS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Signed to Unsigned Template MetaConversions +*****************************************************************************/ + +/** @brief Primary template for signed to unsigned type metafunctions. **/ +template struct Unsigned {}; + +/** @brief Metafunction for char to unsigned char type conversions. **/ +template <> struct Unsigned { typedef unsigned char type; /**< The unsigned equivalent. **/ }; +/** @brief Metafunction for short to unsigned short type conversions. **/ +template <> struct Unsigned { typedef unsigned short type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction for int to unsigned int type conversions. **/ +template <> struct Unsigned { typedef unsigned int type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction for long to unsigned long type conversions. **/ +template <> struct Unsigned { typedef unsigned long type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction for long long to unsigned long long type conversions. **/ +template <> struct Unsigned { typedef unsigned long long type; /**< The unsigned equivalent. **/}; + +/** @brief Metafunction returning same type for unsigned chars. **/ +template <> struct Unsigned { typedef unsigned char type; /**< The unsigned equivalent. **/ }; +/** @brief Metafunction returning same type for unsigned shorts. **/ +template <> struct Unsigned { typedef unsigned short type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction returning same type for unsigned ints. **/ +template <> struct Unsigned { typedef unsigned int type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction returning same type for unsigned longs. **/ +template <> struct Unsigned { typedef unsigned long type; /**< The unsigned equivalent. **/}; +/** @brief Metafunction returning same type for unsigned long longs. **/ +template <> struct Unsigned { typedef unsigned long long type; /**< The unsigned equivalent. **/}; + +} // namespace ecl + +#endif /* ECL_MPL_CONVERTERS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/enable_if.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/enable_if.hpp new file mode 100644 index 0000000..be7a2c1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/enable_if.hpp @@ -0,0 +1,72 @@ +/** + * @file /ecl_mpl/include/ecl/mpl/enable_if.hpp + * + * @brief C++0x's enable_if extensions (fill-in till they're available). + * + * @date 29/07/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_ENABLE_HPP_ +#define ECL_MPL_ENABLE_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Conditional class for (true) implementation of enable_if. + * + * This is not for direct use, it just provides implementation. + */ +template +struct enable_if_c +{ + typedef T type; +}; + +/** + * @brief Conditional class for (false) implementation of enable_if. + * + * This is not for direct use, it just provides implementation. + */ +template +struct enable_if_c +{}; + +/** + * @brief Enables the SFINAE concept. + * + * This is the same as the boost and future C++0x implementations. + * Use this to do things like helping to instantiate families + * of specialisations. For example: + * + * @code +#include // for is_float + +// This will instantiate if it is anything except float or double. +template +class TestObject { +public: + bool isFloatSpecialisation() { return false; } +}; + +// This specialisation will instantiate it T is float or double. +template +class TestObject< T, typename enable_if< is_float >::type > { +public: + bool isFloatSpecialisation() { return true; } +}; + * @endcode + */ +template +struct enable_if : public enable_if_c +{}; + +} //namespace ecl + +#endif /* ECL_MPL_ENABLE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/failed_object.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/failed_object.hpp new file mode 100644 index 0000000..d64ef45 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/failed_object.hpp @@ -0,0 +1,31 @@ +/** + * @file /ecl_mpl/include/ecl/mpl/failed_object.hpp + * + * @brief An object to use when you want to throw a compile time failure. + * + * @date August 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_FAILED_OBJECT_HPP_ +#define ECL_MPL_FAILED_OBJECT_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief An object designed to fail with compile time error upon instantiation. + */ +class FailedObject { +private: + FailedObject() {} +}; + +} // namespace ecl + +#endif /* ECL_MPL_FAILED_OBJECT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/if.hpp b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/if.hpp new file mode 100644 index 0000000..43b5d06 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/include/ecl/mpl/if.hpp @@ -0,0 +1,57 @@ +/** + * @file /include/ecl/mpl/bool.hpp + * + * @brief Defines the metaprogamming equivalent of the boolean type. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_MPL_IF_HPP_ +#define ECL_MPL_IF_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief The metaprogramming equivalent of the 'if' function. + * + * This defines a compile time metafunctional version of the 'if' function. It + * configures the default response (that for when the boolean condition is true). + * The alternative (false) is configured in a specialisation. + * + * @tparam Condition : the logical condition to test. + * @tparam T1 : the return type if true. + * @tparam T2 : the return type if false. + * + * @sa if_c. + */ +template +struct if_c { + typedef T1 type; +}; + +/** + * @brief Specialisation of the metaprogrammed 'if' statement when false. + * + * This defines the negative (false) response for the compile time metafunctional + * version of the 'if' function. + * + * @tparam T1 : the return type if true. + * @tparam T2 : the return type if false. + * + * @sa if_c. + */ +template +struct if_c { + typedef T2 type; +}; + +} // namespace ecl + +#endif /* ECL_MPL_IF_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_mpl/package.xml b/ros2_ws/src/ecl_core/ecl_mpl/package.xml new file mode 100644 index 0000000..af946d5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/package.xml @@ -0,0 +1,32 @@ + + + ecl_mpl + 1.2.1 + + Metaprogramming tools move alot of runtime calculations to be shifted to + compile time. This has only very elementary structures at this stage. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_mpl + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + + ecl_license + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_mpl/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/src/CMakeLists.txt new file mode 100644 index 0000000..8750f10 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/src/CMakeLists.txt @@ -0,0 +1,9 @@ +############################################################################### +# Subdirectories +############################################################################### + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_mpl/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_mpl/src/test/CMakeLists.txt new file mode 100644 index 0000000..3b7dee2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/src/test/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# Gtests +############################################################################### + +ament_add_gtest(test_enable_if enable_if.cpp) diff --git a/ros2_ws/src/ecl_core/ecl_mpl/src/test/enable_if.cpp b/ros2_ws/src/ecl_core/ecl_mpl/src/test/enable_if.cpp new file mode 100644 index 0000000..8299ecd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_mpl/src/test/enable_if.cpp @@ -0,0 +1,99 @@ +/** + * @file /ecl_mpl/src/test/enable_if.cpp + * + * @brief Unit tests for the enable_if template. + * + * @date July 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/mpl/enable_if.hpp" +#include "../../include/ecl/mpl/bool.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::enable_if; + +/***************************************************************************** +** Classes +*****************************************************************************/ + +namespace ecl { +namespace mpl { +namespace tests { + +/***************************************************************************** +** Is Float +*****************************************************************************/ + +template +class is_float : public ecl::False {}; + +template <> +class is_float : public ecl::True {}; + +template <> +class is_float : public ecl::True {}; + +/** + * @brief Default test class. + */ +template +class TestDude { +public: + bool isSpecialisation() { return false; } +}; +/** + * @brief Specialisation of the test class for floats only. + */ +template +class TestDude< T, typename enable_if< is_float >::type > { +public: + bool isSpecialisation() { return true; } +}; + +} // namespace tests +} // namespace mpl +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::mpl::tests; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(EnableIfTests,oneshot) { + TestDude float_dude; + TestDude int_dude; + bool result; + result = float_dude.isSpecialisation(); + EXPECT_EQ(true, result); + result = int_dude.isSpecialisation(); + EXPECT_EQ(false, result); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/.cproject b/ros2_ws/src/ecl_core/ecl_sigslots/.cproject new file mode 100644 index 0000000..a411554 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/.cproject @@ -0,0 +1,702 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + clean + + true + + true + + true + + + + + + make + + test + + true + + true + + true + + + + + + make + + tests + + true + + true + + true + + + + + + make + + + + examples + + true + + true + + true + + + + + + make + + + + all + + true + + true + + true + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/.project b/ros2_ws/src/ecl_core/ecl_sigslots/.project new file mode 100644 index 0000000..7097365 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/.project @@ -0,0 +1,78 @@ + + + ecl_sigslots + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_sigslots/CHANGELOG.rst new file mode 100644 index 0000000..25e1baa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/CHANGELOG.rst @@ -0,0 +1,12 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_sigslots +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.60.8 (2014-02-10) +------------------- + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/CMakeLists.txt new file mode 100644 index 0000000..0f7cace --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/CMakeLists.txt @@ -0,0 +1,75 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_sigslots) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_threads REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + ecl_config::ecl_config + ecl_threads::ecl_threads +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_config + ecl_threads +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/mainpage.dox new file mode 100644 index 0000000..f510611 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/mainpage.dox @@ -0,0 +1,224 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Signals and slots provide a means for communication of events. + The classes here let you have a many-to-many relationship (unlike most event + callback techniques), and also templatise the data transfer to allow the + coder to customise the event data that is communicated from signal to slot. + It also implements a few conditional (event) related classes. + +@section History + + The ideas for this signal/slots implementation come from a few sources. + + - Qt + - SigSlot + - Boost Libraries + + Qt was the original signal/slots implementation, but it needs a pre-processor + to compile the code. Sigslot and Boost on the other hand are pure ISO C++, but + both have some disadvantages. The boost implementation is fairly heavy and a + little cumbersome, although its now morphing into version 2 with even more + functionality (I haven't yet road tested a comparison between the two). + Sigslot was the precursor, is more lightweight, but + has some oddities - it isn't fully typesafed, can't handle global/static + function loading. + + None of these are thread-safe and it can be somewhat inconvenient + manually connecting signal-slot pairs when they are buried far from + each other (e.g. deep in parallel heirarchies of c++ objects). + + This motivated this library - what was needed was an abstract way of + connecting pairs with an engine in the background to do the hard work - ultimately + leaving the programmer free from any tedious details. To do this, the sigslots + library uniquely names connections (i.e. topic name in ros-speak), via a string. Signals + and slots can connect to the topic simply by referring to a string. This + was originally motivated by the way many posix ipc structures connect (e.g. + semaphores and shared memory), but later also merged very neatly with the way + ros topics connect (in particular nodelets). Adding mutex's for thread safety + so that sigslot destruction would occur safely was the next step. + +@section Features + + - Lightweight - implements only the necessary features for practical usage. + - Fully typesafe - signal-slot pairs must have the same type, loaded functions must also agree. + - Slot loading is convenient - global/static and member functions can be loaded with the same api. + - Naming - can use posix style names to identify and perform convenient connections/disconnections. + - Thread safe - slots can disconnect/self-destruct without worrying about segfaulting across threads. + +@section lite Sigslots Lite + + For a light version of sigslots suitable for firmware projects, see ecl_sigslots_lite. + + - No memory allocation on the heap : that is, no malloc, new. + - No string naming : connections done by hand. + - No threads : no dependancy on platform implementations. + +@section Definitions + + @subsection Signals + + Anywhere that triggers an event requiring a callback to be executed can + be implemented with a signal. These can be placed anywhere in your + code and can be connected to one or many slots. + + @subsection Slots + + Anywhere that a callback function is required can be + implemented with a slot. These can be placed anywhere in your code and are + initialised with either a static (global) function, or a member function. + Once initialised, they can be hooked up to a signal. + + @subsection Message Data + + The signal-slot pairs developed here only ever accept one template + argument representing the data to be transmitted from signal to slot. It + would be easy to extend this to more (aka SigSlot/Boost) but I have + yet to find a need for it - if you wish multiple arguments, simply + wrap up your data in a single struct/class. Conceptually, this + makes the code more readable anyway. + + The data class itself could be as simple as an error + id or as complicated as the current state in a fsm. + Note that both signal and slot must use the same type. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The types + using ecl::Signal; + using ecl::Slots; + @endcode + + You will also need to link to -lecl_sigslots. + +\section usage Usage + + @subsection slotLoading Slot Loading + + Loading of slots can be done directly to free or member functions through + the constructors. Below is a simple example for various types of loading. + + @code + void f(const int& i) {} + class A { + public: + void f(const int& i) {} + }; + // ... + A a; + Slot slot0(f); + Slot slot1(&A::f,a); + @endcode + + @subsection connectingUsage Connecting + + @code + Signal signal; + Slot slot(f); + signal.connect("Dudes"); + slot.connect("Dudes"); + @endcode + + Signals and slots have no limit to the number of connections they may make. + + @subsection Emitting + + Every time a signal emits, the connected slots are consecutively run with the data that is emitted. + @code + signal.emit(3); // Pass the '3' to all the slot functions. + @endcode + + Every emit, the slots are consecutively run - this means that your slots should by nature be short and + concise! Otherwise you'll get serious bottlenecks. This is always a good habit to get into for slots + otherwise you'll frequently run into problems. If you have a heavy callback, consider spinning that callback + off into a thread. That way the thread response will still be quick (cost of a thread creation) and you can + still manage heavy workloads. + + @subsection Relaying + + A signal can relay another signal, effectively posing temporarily as a slot. + + @code + @code + Signal<> signal; + Signal<> signal_relay; + Slot<> slot(f); + signal.connect("First_Topic"); + signal_relay.connectAsSlot("First_Topic"); + signal_relay.connect("Second_Topic"); + slot.connect("Second_Topic"); + signal.emit(); + @endcode + + @subsection Debugging + + Often you may wish to see what is actually connected. This can be done by calling the + SigSlotsManager::printStatistics() function. Note that there is a manager for each + templatised family of sigslots (i.e. SigSlotsManager<>, SigSlotsManager). Some + example code: + + @code + A a; + Signal<> sig_void; + + Slot<> slot_void0(g); + Slot<> slot_void1(&A::g,a); + + sig_void.connect("void_test"); + slot_void0.connect("void_test"); + slot_void1.connect("void_test"); + + sig_void.emit(); + ecl::SigSlotsManager<>::printStatistics(); + @endcode + + would print output: + + @code + Topics + Name: void_test + # Subscribers: 2 + # Publishers : 1 + @endcode + + +@section considerations Design Considerations + + - Keep your slot callbacks concise...failing that, reference them or spin the work off into a thread! + - For data slots use const references, saves a copy and prevents your original class losing control of its variables. + - Slots w/ member functions should be member variables of the same class, this guarantees the function is always valid. + - The sigslots manager may become a bottleneck if you are creating/connecting/disconnecting a large number of slots. + + If you do need a sigslot implementation that can handle massive numbers of sigslots, fast connection and disconnection, + then you probably need to look at the old ecl signals or boost/qt. At the moment, we can't foresee a need for that in + control systems, but if needed, this library can be extended. + +@section futureImprovements Future Improvements + + This will be addressed on an 'as needed' basis. + + - Slot loading for nullary and unary function objects. + +\section unitTests Unit Tests + + - src/test/sigslots.cpp + +\section demos Demos + + - src/examples/sigslots.cpp + - src/examples/sigslots_manager.cpp + +\section ChangeLog + + - May 10 : Evolved from the old signals library, adding posix style naming and thread safety. + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/namespaces.dox new file mode 100644 index 0000000..b1fda5c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/doxygen/namespaces.dox @@ -0,0 +1,7 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/include/CMakeLists.txt new file mode 100644 index 0000000..59d1002 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..e3b3664 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(sigslots) + +############################################################################### +# Files +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots.hpp new file mode 100644 index 0000000..a9abc63 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots.hpp @@ -0,0 +1,37 @@ +/** + * @file /include/ecl/sigslots.hpp + * + * @brief File comment + * + * File comment + * + * @date Apr 17, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_HPP_ +#define ECL_SIGSLOTS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ +/* + * Guard against the qt macros. + */ +#ifdef emit + #undef emit + #define replace_qt_emit +#endif + +#include "sigslots/signal.hpp" +#include "sigslots/slot.hpp" + +#ifdef replace_qt_emit + #define emit +#endif + +#endif /* ECL_SIGSLOTS_HPP_ */ + + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/CMakeLists.txt new file mode 100644 index 0000000..5e92b10 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/sigslots) + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/macros.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/macros.hpp new file mode 100644 index 0000000..55c8f93 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/sigslot/macros.hpp + * + * @brief Macros for ecl sigslots. + * + * @date May, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_MACROS_HPP_ +#define ECL_SIGSLOTS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_sigslots_EXPORTS // we are building a shared lib/dll + #define ecl_sigslots_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_sigslots_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_sigslots_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_sigslots_PUBLIC + #define ecl_sigslots_LOCAL +#endif + +#endif /* ECL_SIGSLOTS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/manager.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/manager.hpp new file mode 100644 index 0000000..f1c79a2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/manager.hpp @@ -0,0 +1,178 @@ +/** + * @file /ecl_sigslots/include/ecl/sigslots/manager.hpp + * + * @brief File comment + * + * File comment + * + * @date 13/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_MANAGER_HPP_ +#define ECL_SIGSLOTS_MANAGER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "topic.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface +*****************************************************************************/ +/** + * @brief The sigslots connection manager. + * + * This handles all the connections via the unique string identifiers. It does + * this invisibly, so the programmer need not actually have to use this + * class. However, it may be useful for debugging to actually check the number + * of connections with the printStatistics() method. + * + * @tparam Data : the type of sigslots this manager looks after. + */ +template +class SigSlotsManager { +public: + + friend class SigSlot; + + /** + * @brief Print some statistics on the current status of the manager. + * + * Only here for debugging purposes only. + */ + static void printStatistics() { + std::cout << "Topics" << std::endl; + typename std::map< std::string, Topic >::iterator iter; + for ( iter = topics().begin(); iter != topics().end(); ++iter ) { + std::cout << iter->second; + } + } + +private: + /** + * @brief A list of subscribers (slots) to a given topic. + */ + typedef typename Topic::Subscribers Subscribers; + + /** + * Connects the signal to the topic if it already exists, or creates + * the topic if it doesn't. Returns the subscriber list which is used by + * sigslot to bypass the manager when emitting. + * + * @param topic : topic to publish to. + * @param sigslot : sigslot that will be publishing. + * @return const Subscribers& : a reference to the subscriber list. + */ + static const Subscribers* connectSignal(const std::string& topic, SigSlot* sigslot) { + // Try and insert a new topic in case it doesn't already exist + // In any case, we always get the iterator back (to new or existing) + // + // Maybe improve the efficiency of this by specifying position + // refer to http://www.cplusplus.com/reference/stl/map/insert/ + std::pair< typename std::map< std::string, Topic >::iterator,bool> ret = topics().insert( std::pair< std::string, Topic >(topic, Topic(topic)) ); + Topic& current_topic = (ret.first)->second; + current_topic.addPublisher(sigslot); + return current_topic.subscribers(); + } + + /** + * Connects the slot to the topic if it already exists, or creates + * the topic if it doesn't. + * + * @param topic : topic to subscribe (listen) to. + * @param sigslot : sigslot that will be subscribing (listening). + */ + static void connectSlot(const std::string& topic, SigSlot* sigslot) { + // Try and insert a new topic in case it doesn't already exist + // In any case, we always get the iterator back (to new or existing) + // + // Maybe improve the efficiency of this by specifying position + // refer to http://www.cplusplus.com/reference/stl/map/insert/ + std::pair< typename std::map< std::string, Topic >::iterator,bool> ret = topics().insert(std::pair< std::string, Topic >(topic, Topic(topic)) ); + Topic& current_topic = (ret.first)->second; + current_topic.addSubscriber(sigslot); + } + + /** + * @brief Disconnect the sigslot from the specified topic. + * + * This disconnection works for both signals and slots. + * + * @param topic : topic that the sigslot must be disconnected from. + * @param sigslot : the sigslots that is to be disconnected. + */ + static void disconnect(const std::string& topic, SigSlot* sigslot) { + typename std::map >::iterator iter = topics().find(topic); + if ( iter != topics().end() ) { + iter->second.disconnect(sigslot); + } + if ( iter->second.empty() ) { + topics().erase(iter); + } + } + + /** + * @brief Check to see if the specified topic exists (and is being used). + * + * @param topic : topic to check. + * @return bool : success/failure of the request. + */ + static bool isTopic(const std::string& topic) { + return !( topics().find(topic) == topics().end() ); + } + + /** + * @brief Hack to create a static variable internally without. + * + * Simple trick to avoid the explicit instantiation in a library. + * + * @return map : a handle to the string id/topic database. + */ + static std::map< std::string, Topic >& topics() { + static std::map< std::string, Topic > topic_list; + return topic_list; + } + + /** + * @brief Provides a list of subscribers (listeners) associated with a topic. + * + * This provides a handle to the list of subscribers to a topic. Used by + * the signals to keep track of who's following them and who to run when + * emitting. + * + * @param topic : the topic to check for. + * @return Subscribers : a set of pointers to subscribers of a topic. + */ + static const Subscribers& subscribers(const std::string& topic) { + typename std::map< std::string, Topic >::const_iterator iter = topics().find(topic); + /* + * Note that this is called only by SigSlotsManager::connectSignal which + * makes sure the topic name exists, so we don't need to do any error + * handling here. + */ + // ecl_assert_throw( iter != topics().end(), StandardException(LOC,InvalidInputError,std::string("No sigslots topic with name:")+topic) ); + return *iter->second.subscribers(); + } + +}; + +} // namespace ecl + + +#endif /* ECL_SIGSLOTS_MANAGER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/signal.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/signal.hpp new file mode 100644 index 0000000..843caa6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/signal.hpp @@ -0,0 +1,249 @@ +/** + * @file /ecl_sigslots/include/ecl/sigslots/signal.hpp + * + * @brief File comment + * + * File comment + * + * @date 13/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_SIGNAL_HPP_ +#define ECL_SIGSLOTS_SIGNAL_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "sigslot.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [General] +*****************************************************************************/ +/** + * @brief Signalling component of a callback system. + * + * Anywhere that triggers an event requiring a callback to be + * executed can be implemented with a signal. These can be placed anywhere in your + * code and with slots, provide a many to many callback solution. + * + * Usage examples are provided in the main page's documentation for this package. + * + * @sa Signal, Slot. + **/ + +template +class ECL_PUBLIC Signal { +public: + /** + * @brief Default constructor. + * + * This creates a signal with no connections yet established. + * Use with connect(). + */ + Signal() : sigslot(NULL) { + sigslot = new SigSlot(); + } + /** + * @brief Creates a signal and connects. + */ + Signal(const std::string &topic) : sigslot(NULL) { + sigslot = new SigSlot(); + connect(topic); + } + + /** + * @brief Copy constructor. + * + * This is specially designed so that copying a signal is perfectly + * acceptable. Copies do not increase the number of emits that + * are fired - they just preserve the signal when used with + * things like stl containers. When the last copy disappears, + * the object destroys its connection automagically. + * + * @param signal : the object to be copied. + */ + Signal(const Signal& signal) { + *this = signal; + sigslot->incrHandles(); + } + + /** + * @brief Default destructor. + * + * This handles the cleanup operation, first decrementing and then + * checking if its the last of its instance. If it is, it cleans + * up the sigslot connection with the sigslots manager. + */ + ~Signal() { + sigslot->decrHandles(); + if ( sigslot->handles() == 0 ) { + delete sigslot; + } + } + + /** + * @brief Default assignment operator. + */ + void operator=( const Signal& signal) { + sigslot = signal.sigslot; + } + + /** + * @brief Make a connection to the specified topic. + * + * This contacts the sigslots manager to connect the signal to the + * specified topic - creating the topic if it is not yet existing. + * + * @param topic : the topic to connect to. + */ + void connect(const std::string& topic) { sigslot->connectSignal(topic); } + /** + * @brief Connect as a slot, with the emit function loaded. + * + * This allows the signal to act as a relaying signal (effectively + * a slot with the emit() function loaded. + * + * @param topic : the topic to connect to. + */ + void connectAsSlot(const std::string& topic) { sigslot->connectSlot(topic); } + /** + * @brief Disconnect the signal from all topics. + * + * This completely disconnects the signal. + */ + void disconnect() { sigslot->disconnect(); } + + /** + * @brief The primary purpose of the signal, to emit! + * + * Emits a signal with the specified data. + * + * @param data : the data to emit. + */ + void emit(Data data) { sigslot->emit(data); } + +private: + SigSlot* sigslot; +}; + +/***************************************************************************** +** Interface [Void] +*****************************************************************************/ +/** + * @brief Specialised signal that emits without passing data. + * + * Specialised signal that only emits a signal but passes no data to their + * respective slots. This is the default template construction for a + * signal, so you need only use Signal<> to represent the type. + * + * Usage examples are provided in the main page's documentation for this package. + * + * @sa Signal, Slot. +**/ +template<> +class ECL_PUBLIC Signal { +public: + /** + * @brief Default constructor. + * + * This creates a signal but with no default connection. Use + * connect() to establish a connection. + */ + Signal() : sigslot(NULL) { + sigslot = new SigSlot(); + } + /** + * @brief Creates a signal and connects. + */ + Signal(const std::string &topic) : sigslot(NULL) { + sigslot = new SigSlot(); + connect(topic); + } + /** + * @brief Copy constructor. + * + * This is specially designed so that copying a signal is perfectly + * acceptable. Copies do not increase the number of emits that + * are fired - they just preserve the signal when used with + * things like stl containers. When the last copy disappears, + * the object destroys its connection automagically. + * + * @param signal : the object to be copied. + */ + Signal(const Signal& signal) { + *this = signal; + sigslot->incrHandles(); + } + + /** + * @brief Default assignment operator. + */ + void operator=( const Signal& signal) { + sigslot = signal.sigslot; + } + + /** + * @brief Default destructor. + * + * This handles the cleanup operation, first decrementing and then + * checking if its the last of its instance. If it is, it cleans + * up the sigslot connection with the sigslots manager. + */ + ~Signal() { + sigslot->decrHandles(); + if ( sigslot->handles() == 0 ) { + delete sigslot; + } + } + /** + * @brief Make a connection to the specified topic. + * + * This contacts the sigslots manager to connect the signal to the + * specified topic - creating the topic if it is not yet existing. + * + * @param topic : the topic to connect to. + */ + void connect(const std::string& topic) { sigslot->connectSignal(topic); } + /** + * @brief Connect as a slot, with the emit function loaded. + * + * This allows the signal to act as a relaying signal (effectively + * a slot with the emit() function loaded. + * + * @param topic : the topic to connect to. + */ + void connectAsSlot(const std::string& topic) { sigslot->connectSlot(topic); } + /** + * @brief Disconnect the signal from all topics. + * + * This completely disconnects the signal. + */ + void disconnect() { sigslot->disconnect(); } + + /** + * @brief The primary purpose of the signal, to emit! + * + * Emits a signal with no data. + */ + void emit() { sigslot->emit(); } + +private: + SigSlot* sigslot; + +}; + +} // namespace ecl + +#endif /* ECL_SIGSLOTS_SIGNAL_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/sigslot.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/sigslot.hpp new file mode 100644 index 0000000..4e36dad --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/sigslot.hpp @@ -0,0 +1,364 @@ +/** + * @file /ecl_sigslots/include/ecl/sigslots/sigslot.hpp + * + * @brief File comment + * + * File comment + * + * @date 13/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_SIGSLOT_HPP_ +#define ECL_SIGSLOTS_SIGSLOT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "manager.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [General] +*****************************************************************************/ +/** + * @brief Not for direct use, provides the power behind both signals and slots. + * + * This is the workhorse for both signals and slots, providing the implementation + * for all the functions necessary by both types of frontends. + */ +template +class SigSlot { +public: + /********************* + ** Typedefs + **********************/ + typedef typename Topic::Subscribers Subscribers; /**< @brief A list of subscribers (slots) to a given topic. **/ + typedef typename std::map PublicationMap; /**< @brief Stores publishing topics and their followers. **/ + + /********************* + ** C&D + **********************/ + /** + * Used only by signals where the function callback automatically + * defaults to the emit() function. + */ + SigSlot() : processing_count(0), number_of_handles(1) { + function = new PartiallyBoundUnaryMemberFunction< SigSlot ,Data,void >( &SigSlot::emit, *this); + } + /** + * Used by slots loading global or static functions. + * + * @param f : the global/static function. + */ + SigSlot(void (*f)(Data)) : processing_count(0), number_of_handles(1) { + function = new UnaryFreeFunction(f); + } + /** + * Used by slots loading a member function. + * + * @param f : the member function to load. + * @param c : the instance for the member function's class. + * @tparam C : the member function's class type. + */ + template + SigSlot(void (C::*f)(Data), C &c) : processing_count(0), number_of_handles(1) { + function = new PartiallyBoundUnaryMemberFunction(f,c); + } + + /** + * @brief Disconnects the sigslot completely. + * + * This is a rather elaborate process, it must first disconnect from any signals + * to ensure no new callbacks are instantiated, then check to see that there + * are no callbacks actually running, block if so, then finalise any deletions. + */ + ~SigSlot() { + disconnect(); // stop any new processing from connected signals + mutex.lock(); // acts like a barrier - holds up here if function still processing stuff. + delete function; + } + + const unsigned int& handles() const { return number_of_handles; } /**< @brief Number of copies of this object. **/ + void incrHandles() { ++number_of_handles; } /**< @brief Increment the counter for the number of copies of this object. **/ + void decrHandles() { --number_of_handles; } /**< @brief Decrement the counter for the number of copies of this object. **/ + + /** + * @brief Emit a signal along with the specified data. + * + * This is used by signals when emitting to slots. + */ + void emit(Data data) { + typename PublicationMap::const_iterator topic_iter; + typename Subscribers::const_iterator slots_iter; + for ( topic_iter = publications.begin(); topic_iter != publications.end(); ++topic_iter ) { + const Subscribers* subscribers = topic_iter->second; + for ( slots_iter = subscribers->begin(); slots_iter != subscribers->end(); ++slots_iter ) { + SigSlot *sigslot = *slots_iter; + sigslot->process(data); + } + } + } + /** + * @brief Process the callback function loaded into this sigslot. + * + * This is used by slots with their loaded functions or relaying + * signals with their emit() methods. + */ + void process(Data data) { + mutex.trylock(); // Only lock if its not already locked. + ++processing_count; + (*function)(data); + if ( --processing_count == 0 ) { + mutex.unlock(); + } + } + /** + * @brief Connect a signal to the specified topic. + * + * If the topic doesn't exist, it will be created and the signal + * connected. If it does exist, it will connect with a set of + * slots also currently linked to the topic. + */ + void connectSignal(const std::string& topic) { + // Logic: + // - if already publishing to this topic + // - don't do anything + // - else + // - if topic doesn't exist + // - Manager will automatically create a new topic + // - Manager returns the subscribers handle + // - Topic name and subscribers handle are stored locally here in publications + publications.insert( std::pair(topic, SigSlotsManager::connectSignal(topic,this)) ); + } + /** + * @brief Connect a slot to the specified topic. + * + * If the topic doesn't exist, it will be created and the slot + * connected. If it does exist, it will pass on its link + * details to any signals also connected to the topic. + */ + void connectSlot(const std::string& topic) { + std::pair< std::set::iterator,bool > ret; + // std::cout << "Topic: " << topic << std::endl; + ret = subscriptions.insert(topic); // Doesn't matter if it already exists. + if ( ret.second ) { + SigSlotsManager::connectSlot(topic,this); + } // else { already subscribed to this topic } + } + /** + * @brief Disconnect the sigslot from the specified topic. + */ + void disconnect(const std::string &topic) { + // std::set::const_iterator listen_iter = subscriptions.find(topic); + publications.erase(topic); // Doesn't matter if it finds it or not. + SigSlotsManager::disconnect(topic,this); + } + /** + * @brief Disconnect the sigslot from all topics. + * + * This completely disconnects the sigslot. + */ + void disconnect() { + std::set::iterator iter; + for ( iter = subscriptions.begin(); iter != subscriptions.end(); ++iter ) { + SigSlotsManager::disconnect(*iter, this); + } + subscriptions.clear(); + typename std::map::iterator emit_iter; + for ( emit_iter = publications.begin(); emit_iter != publications.end(); ++emit_iter ) { + SigSlotsManager::disconnect(emit_iter->first, this); + } + publications.clear(); + } + + const std::set& subscribedTopics() { return subscriptions; } + +private: + Mutex mutex; + unsigned int processing_count; // number of running process()' + unsigned int number_of_handles; // number of handles to this sigslot (allows copying) + std::set subscriptions; // topics this sigslot is listening to + PublicationMap publications; // topics this sigslot is posting to, as well as the subscribers on the other end + + UnaryFunction *function; +}; + +/***************************************************************************** +** Interface [Void] +*****************************************************************************/ + +/** + * @brief Not for direct use, provides the power behind both void signals and slots. + * + * This is the workhorse for both signals and slots, providing the implementation + * for all the functions necessary by both types of frontends. This is the + * specialisation of the general case for void callbacks. + */ +template<> +class SigSlot { +public: + // typedef std::set*> Subscribers + typedef Topic::Subscribers Subscribers; /**< @brief A list of subscribers (slots) to a given topic. **/ + typedef std::map PublicationMap; /**< @brief Stores publishing topics and their followers. **/ + + /** + * Used only by signals where the function callback automatically + * defaults to the emit() function. + */ + SigSlot() : processing_count(0), number_of_handles(1) { + function = new BoundNullaryMemberFunction(&SigSlot::emit,*this); + } + /** + * Used by slots loading global or static functions. + * + * @param f : the global/static function. + */ + SigSlot(VoidFunction f) : processing_count(0), number_of_handles(1) { + function = new NullaryFreeFunction(f); + } + /** + * Used by slots loading a member function. + * + * @param f : the member function to load. + * @param c : the instance for the member function's class. + * @tparam C : the member function's class type. + */ + template + SigSlot(void (C::*f)(void), C &c) : processing_count(0), number_of_handles(1) { + function = new BoundNullaryMemberFunction(f,c); + } + + /** + * @brief Disconnects the sigslot completely. + * + * This is a rather elaborate process, it must first disconnect from any signals + * to ensure no new callbacks are instantiated, then check to see that there + * are no callbacks actually running, block if so, then finalise any deletions. + */ + ~SigSlot() { + disconnect(); // stop any new processing from connected signals + mutex.lock(); // acts like a barrier - holds up here if function still processing stuff. + delete function; + } + + const unsigned int& handles() const { return number_of_handles; } /**< @brief Number of copies of this object. **/ + void incrHandles() { ++number_of_handles; } /**< @brief Increment the counter for the number of copies of this object. **/ + void decrHandles() { --number_of_handles; } /**< @brief Decrement the counter for the number of copies of this object. **/ + + /** + * @brief Emit a signal. + * + * This is used by signals when emitting to slots. + */ + void emit() { + PublicationMap::const_iterator topic_iter; + Subscribers::const_iterator slots_iter; + for ( topic_iter = publications.begin(); topic_iter != publications.end(); ++topic_iter ) { + const Subscribers* subscribers = topic_iter->second; + for ( slots_iter = subscribers->begin(); slots_iter != subscribers->end(); ++slots_iter ) { + SigSlot *sigslot = *slots_iter; + sigslot->process(); + } + } + } + /** + * @brief Process the callback function loaded into this sigslot. + * + * This is used by slots with their loaded functions or relaying + * signals with their emit() methods. + */ + void process(Void void_arg = Void()) { + (void)void_arg; + mutex.trylock(); // Only lock if its not already locked. + ++processing_count; + (*function)(); + if ( --processing_count == 0 ) { + mutex.unlock(); + } + } + /** + * @brief Connect a signal to the specified topic. + * + * If the topic doesn't exist, it will be created and the signal + * connected. If it does exist, it will connect with a set of + * slots also currently linked to the topic. + */ + void connectSignal(const std::string& topic) { + // Logic: + // - if already publishing to this topic + // - don't do anything + // - else + // - if topic doesn't exist + // - Manager will automatically create a new topic + // - Manager returns the subscribers handle + // - Topic name and subscribers handle are stored locally here in publications + publications.insert( std::pair(topic, SigSlotsManager::connectSignal(topic,this)) ); + } + /** + * @brief Connect a slot to the specified topic. + */ + void connectSlot(const std::string& topic){ + std::pair< std::set::iterator,bool > ret; + ret = subscriptions.insert(topic); // Doesn't matter if it already exists. + if ( ret.second ) { + SigSlotsManager::connectSlot(topic,this); + } // else { already subscribed to this topic } + } + /** + * @brief Disconnect the sigslot from the specified topic. + * + * If the topic doesn't exist, it will be created and the slot + * connected. If it does exist, it will pass on its link + * details to any signals also connected to the topic. + */ + void disconnect(const std::string &topic) { + publications.erase(topic); // Doesn't matter if it finds it or not. + SigSlotsManager::disconnect(topic,this); + } + /** + * @brief Disconnect the sigslot from all topics. + * + * This completely disconnects the sigslot. + */ + void disconnect() { + std::set::iterator iter; + for ( iter = subscriptions.begin(); iter != subscriptions.end(); ++iter ) { + SigSlotsManager::disconnect(*iter, this); + } + subscriptions.clear(); + std::map::iterator emit_iter; + for ( emit_iter = publications.begin(); emit_iter != publications.end(); ++emit_iter ) { + SigSlotsManager::disconnect(emit_iter->first, this); + } + publications.clear(); + } + +private: + Mutex mutex; + unsigned int processing_count; // number of running process()' + unsigned int number_of_handles; // number of handles to this sigslot (allows copying) + std::set subscriptions; // topics this sigslot is listening to + PublicationMap publications; // topics this sigslot is posting to, as well as the subscribers on the other end + + NullaryFunction *function; +}; + +} // namespace ecl + +#endif /* ECL_SIGSLOTS_SIGSLOT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/slot.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/slot.hpp new file mode 100644 index 0000000..d6bed73 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/slot.hpp @@ -0,0 +1,296 @@ +/** + * @file /ecl_sigslots/include/ecl/sigslots/slot.hpp + * + * @brief File comment + * + * File comment + * + * @date 13/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_SLOT_HPP_ +#define ECL_SIGSLOTS_SLOT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "sigslot.hpp" +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [General] +*****************************************************************************/ + +/** + * @brief Function loading component of a callback system. + * + * Anywhere that a callback is required can be implemented with a slot. These + * can be placed anywhere in your code and are initialised with either a free + * (static or global) function, or a member function. Once initialised, they can + * be hooked up to a signal. + * + * Usage examples are provided in the main page's documentation for this package. + * + * @sa Signal, Slot. + **/ +template +class ECL_PUBLIC Slot { +public: + /** + * @brief Load with a global/static function. + * + * Note that the function must have exactly one argument and it must + * be of the same type as the slot. It also must return void. + * + * @param f : the global/static function. + */ + Slot(void (*f)(Data)) : sigslot(NULL) { + sigslot = new SigSlot(f); + } + /** + * @brief Load with a global/static function and connect. + * + * Note that the function must have exactly one argument and it must + * be of the same type as the slot. It also must return void. + * + * It additionally connects to the specified topic rapi style. + * + * @param f : the global/static function. + * @param topic : the slot topic name to connect to. + */ + Slot(void (*f)(Data), const std::string &topic) : sigslot(NULL) { + sigslot = new SigSlot(f); + connect(topic); + } + + /** + * @brief Load with a member function. + * + * Note that the function must have exactly one argument and it must + * be of the same type as the slot. It also must return void. + * + * @param f : the member function. + * @param c : the class instance. + */ + template + Slot(void (C::*f)(Data), C &c) : sigslot(NULL) { + sigslot = new SigSlot(f,c); + } + /** + * @brief Load with a member function and connect. + * + * Note that the function must have exactly one argument and it must + * be of the same type as the slot. It also must return void. + * + * It additionally connects to the specified topic rapi style. + * + * @param f : the member function. + * @param c : the class instance. + * @param topic : the slot topic name to connect to. + */ + template + Slot(void (C::*f)(Data), C &c, const std::string& topic) : sigslot(NULL) { + sigslot = new SigSlot(f,c); + connect(topic); + } + + /** + * @brief Copy constructor. + * + * This is specially designed so that copying a slot is perfectly + * acceptable. Copies do not increase the number of callbacks that + * are fired - they just preserve the slot when used with + * things like stl containers. When the last copy disappears, + * the object destroys its connection automagically. + * + * @param slot : the object to be copied. + */ + Slot(const Slot& slot) { + *this = slot; + sigslot->incrHandles(); + } + + /** + * @brief Default destructor. + * + * This handles the cleanup operation, first decrementing and then + * checking if its the last of its instance. If it is, it cleans + * up the sigslot connection with the sigslots manager. + */ + ~Slot() { + sigslot->decrHandles(); + if ( sigslot->handles() == 0 ) { + delete sigslot; + } + } + /** + * @brief Default assignment operator. + */ + void operator=( const Slot& slot) { + sigslot = slot.sigslot; + } + /** + * @brief Lists the topics this slot is connected to. + * + * Useful for debugging. + * @return set : a set of topic names this slot is listening to. + */ + const std::set& connections() { return sigslot->subscribedTopics(); } + /** + * @brief Make a connection to the specified topic. + * + * This contacts the sigslots manager to connect the signal to the + * specified topic - creating the topic if it is not yet existing. + * + * @param topic : the topic to connect to. + */ + void connect(const std::string& topic) { sigslot->connectSlot(topic); } + /** + * @brief Disconnect the slot from all topics. + * + * This completely disconnects the slot. + */ + void disconnect() { sigslot->disconnect(); } + +private: + SigSlot* sigslot; +}; + +/***************************************************************************** +** Interface [Void] +*****************************************************************************/ +/** + * @brief Specialised slot that handles void callbacks. + * + * Specialised signal that works with void function callbacks. + * + * Usage examples are provided in the main page's documentation for this package. + * + * @sa Signal, Slot. + **/ +template<> +class ECL_PUBLIC Slot { +public: + /** + * @brief Load with a global/static function. + * + * Note that the function must have zero arguments and it must + * return void. + * + * @param f : the global/static function. + */ + Slot(VoidFunction f) : sigslot(NULL) { + sigslot = new SigSlot(f); + } + /** + * @brief Load with a global/static function and connect. + * + * Note that the function must have zero arguments and it must + * return void. + * + * @param f : the global/static function. + * @param topic : the slot topic name to connect to. + */ + Slot(VoidFunction f, const std::string &topic) : sigslot(NULL) { + sigslot = new SigSlot(f); + connect(topic); + } + /** + * @brief Load with a member function. + * + * Note that the function must have zero arguments and it must + * return void. + * + * @param f : the member function. + * @param c : the class instance. + */ + template + Slot(void (C::*f)(void), C &c) : sigslot(NULL) { + sigslot = new SigSlot(f,c); + } + /** + * @brief Load with a member function and connect. + * + * Note that the function must have zero arguments and it must + * return void. + * + * @param f : the member function. + * @param c : the class instance. + * @param topic : the slot topic name to connect to. + */ + template + Slot(void (C::*f)(void), C &c, const std::string &topic) : sigslot(NULL) { + sigslot = new SigSlot(f,c); + connect(topic); + } + /** + * @brief Copy constructor. + * + * This is specially designed so that copying a slot is perfectly + * acceptable. Copies do not increase the number of callbacks that + * are fired - they just preserve the slot when used with + * things like stl containers. When the last copy disappears, + * the object destroys its connection automagically. + * + * @param slot : the object to be copied. + */ + Slot(const Slot& slot) { + *this = slot; + sigslot->incrHandles(); + } + /** + * @brief Default destructor. + * + * This handles the cleanup operation, first decrementing and then + * checking if its the last of its instance. If it is, it cleans + * up the sigslot connection with the sigslots manager. + */ + ~Slot() { + sigslot->decrHandles(); + if ( sigslot->handles() == 0 ) { + delete sigslot; + } + } + /** + * @brief Default assignment operator. + */ + void operator=( const Slot& slot) { + sigslot = slot.sigslot; + } + /** + * @brief Make a connection to the specified topic. + * + * This contacts the sigslots manager to connect the signal to the + * specified topic - creating the topic if it is not yet existing. + * + * @param topic : the topic to connect to. + */ + void connect(const std::string& topic) { sigslot->connectSlot(topic); } + /** + * @brief Disconnect the slot from all topics. + * + * This completely disconnects the slot. + */ + void disconnect() { sigslot->disconnect(); } + +private: + SigSlot* sigslot; + +// unused: +// unsigned int copies() { return sigslot->handles(); } +}; + +} // namespace ecl + +#endif /* ECL_SIGSLOTS_SLOT_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/topic.hpp b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/topic.hpp new file mode 100644 index 0000000..5037e59 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/include/ecl/sigslots/topic.hpp @@ -0,0 +1,142 @@ +/** + * @file /ecl_sigslots/include/ecl/sigslots/topic.hpp + * + * @brief Simple structure holding publishers and subscribers to a topic. + * + * @date 13/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_TOPIC_HPP_ +#define ECL_SIGSLOTS_TOPIC_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +template +class SigSlot; + +/***************************************************************************** +** Interface +*****************************************************************************/ +/** + * @brief Stores publisher and subscriber lists to a uniquely string identified topic. + * + * This is not for direct use, its the storage container for the sigslots manager. + */ +template +class ECL_LOCAL Topic { +public: + /********************* + ** Typedefs + **********************/ + typedef std::set*> Subscribers; /**< @brief A list of subscribers (slots) to a given topic. **/ + + /** + * @brief Uniquely construct with the specified name. + * @param name : name of the topic. + */ + Topic(const std::string& name) : topic_name(name) {} + + /** + * @brief List of subscribers (listeners) to a topic. + * @return Subscribers : handle to the list. + */ + const Subscribers* subscribers() const { return &topic_subscribers; } + + /** + * @brief Add a subscriber. + * @param sigslot : the sigslot to add. + */ + void addSubscriber(SigSlot* sigslot) { + topic_subscribers.insert(sigslot); + } + /** + * @brief Add a publisher. + * @param sigslot : the sigslot to add. + */ + void addPublisher(SigSlot* sigslot) { + topic_publishers.insert(sigslot); + } + /** + * @brief Disconnect a sigslot. + * + * This parses both publishers and subscribers looking for the sigslot to connect. + * Could be a bit heavy doing it this way, but its convenient. + * + * @param sigslot : the sigslot to disconnect. + */ + void disconnect(SigSlot* sigslot) { + typename std::set*>::const_iterator iter = topic_publishers.find(sigslot); + if ( iter != topic_publishers.end() ) { + topic_publishers.erase(iter); + } + iter = topic_subscribers.find(sigslot); + if ( iter != topic_subscribers.end() ) { + topic_subscribers.erase(iter); + } + } + /** + * @brief Checks to see if there is no publishers/subscribers. + * + * This is used to delete the topic (by the manager) if it is empty. + * @return bool : empty (true) or not (false). + */ + bool empty() const { + return ( ( topic_publishers.size() == 0 ) && ( topic_subscribers.size() == 0 ) ); + } + + /********************* + ** Streaming + **********************/ + /** + * Insertion operator for sending the topic to an output stream. + * @param ostream : the output stream. + * @param topic : the topic to be inserted. + * @return OutputStream : continue streaming with the updated output stream. + */ + template + friend OutputStream& operator<<(OutputStream &ostream , const Topic& topic); + +private: + std::string topic_name; + std::set*> topic_publishers; + std::set*> topic_subscribers; +}; + + +/***************************************************************************** +** Implementation [Streaming] +*****************************************************************************/ + +template +OutputStream& operator<<(OutputStream &ostream , const Topic &topic) { + + ostream << " Name: " << topic.topic_name << "\n"; + ostream << " # Subscribers: " << topic.topic_subscribers.size() << "\n"; + ostream << " # Publishers : " << topic.topic_publishers.size() << "\n"; + ostream.flush(); + + return ostream; +} + +} // namespace ecl + +#endif /* ECL_SIGSLOTS_TOPIC_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/package.xml b/ros2_ws/src/ecl_core/ecl_sigslots/package.xml new file mode 100644 index 0000000..95f9f6a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/package.xml @@ -0,0 +1,39 @@ + + + ecl_sigslots + 1.2.1 + + Provides a signal/slot mechanism (in the same vein as qt sigslots, + boost::signals etc for intra-process communication. These include + some improvements - they do not need a preprocessor, are fully type safe, + allow for simple connections via a posix style string identifier + and are multithread-safe. + + Daniel Stonier + BSD-3-Clause + http://ros.org/wiki/ecl_sigslots + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_threads + + ecl_license + ecl_config + ecl_threads + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/src/CMakeLists.txt new file mode 100644 index 0000000..d81060b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/CMakeLists.txt @@ -0,0 +1,12 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(examples) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/CMakeLists.txt new file mode 100644 index 0000000..f40c878 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/CMakeLists.txt @@ -0,0 +1,23 @@ +############################################################################## +# Macros +############################################################################## + +macro(ecl_sigslots_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries( + ecl_demo_${name} + PUBLIC + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_threads::ecl_threads + ) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################## +# Executables +############################################################################## + +ecl_sigslots_add_demo(sigslots) +ecl_sigslots_add_demo(sigslots_manager) diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots.cpp b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots.cpp new file mode 100644 index 0000000..06a69a5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots.cpp @@ -0,0 +1,171 @@ +/** + * @file /src/examples/sigslots.cpp + * + * @brief Fairly comprehensive demo of the sigslot api. + * + * @date May 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/sigslots.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Signal; +using ecl::Slot; +using ecl::SigSlotsManager; + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Globals +*****************************************************************************/ + +void f() { + std::cout << " ---> Hey Dude" << std::endl; +} + +void g() { + std::cout << " ---> Hey Chained Dude" << std::endl; +} + +void h(const int& i) { + std::cout << " ---> Hey Data Dude: " << i << std::endl; +} + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class A { +public: + A() : slot(&A::f,*this), slot_data(&A::g,*this) { + slot.connect("Dudette"); + slot_data.connect("DataDudette"); + }; + + void f() { + std::cout << " ---> Hey Dudette" << std::endl; + } + void g(const int& i) { + std::cout << " ---> Hey Data Dudette: " << i << std::endl; + } + Slot<> slot; + Slot slot_data; +}; + +/** + * @endcond + */ +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /* argc */, char** /* argv */ ) { + + std::cout << "Hello dude" << std::endl; + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Global Function" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + Slot<> slot1(&f); + Slot<> slot2(&f); + std::cout << "Connecting 1 signal and two slots to 'Dude'" << std::endl; + slot1.connect("Dude"); + slot2.connect("Dude"); + Signal<> signal; + signal.connect("Dude"); + std::cout << "Emitting" << std::endl; + signal.emit(); + std::cout << std::endl; + SigSlotsManager<>::printStatistics(); + std::cout << std::endl; + + std::cout << "Connecting a data slot-signal pair to 'DataDude'" << std::endl; + Slot slot_data_1(&h); + Signal sig_data_1; + slot_data_1.connect("DataDude"); + sig_data_1.connect("DataDude"); + std::cout << "Emitting" << std::endl; + sig_data_1.emit(2); + std::cout << std::endl; + SigSlotsManager::printStatistics(); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Disconnects" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Disconnecting second slot" << std::endl; + slot2.disconnect(); + std::cout << "Emitting" << std::endl; + signal.emit(); + std::cout << "Disconnecting signal" << std::endl; + signal.disconnect(); + std::cout << "Emitting (to nowhere)" << std::endl; + signal.emit(); + std::cout << std::endl; + SigSlotsManager<>::printStatistics(); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Relays" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Connecting signal and second slot back to 'Dude'" << std::endl; + slot2.connect("Dude"); + signal.connect("Dude"); + std::cout << std::endl; + SigSlotsManager<>::printStatistics(); + std::cout << std::endl; + + Signal<> signal_relay; + std::cout << "Connecting relay as signal to 'ChainedDude'" << std::endl; + signal_relay.connect("ChainedDude"); + std::cout << "Connecting relay as slot to 'Dude'." << std::endl; + signal_relay.connectAsSlot("Dude"); + Slot<> slot3(&g); + std::cout << "Connecting slot to 'ChainedDude'" << std::endl; + slot3.connect("ChainedDude"); + std::cout << "Emitting" << std::endl; + signal.emit(); + std::cout << std::endl; + SigSlotsManager<>::printStatistics(); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Member Functions" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Creating a member slot and connecting to 'Dudette'" << std::endl; + A a; + std::cout << "Connecting a signal to 'Dudette'" << std::endl; + Signal<> signal_dudette; + signal_dudette.connect("Dudette"); + signal_dudette.emit(); + SigSlotsManager<>::printStatistics(); + std::cout << std::endl; + + std::cout << "Creating a member data slot and connecting to 'DataDudette'" << std::endl; + std::cout << "Connecting a data signal to 'DataDudette'" << std::endl; + Signal signal_data_dudette; + signal_data_dudette.connect("DataDudette"); + signal_data_dudette.emit(3); + std::cout << std::endl; + SigSlotsManager::printStatistics(); + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots_manager.cpp b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots_manager.cpp new file mode 100644 index 0000000..70f19dc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/examples/sigslots_manager.cpp @@ -0,0 +1,101 @@ +/** + * @file /ecl_sigslots/src/examples/sigslots_manager.cpp + * + * @brief Demonstration of how to debug with SigSlotsManager. + * + * @date March 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/sigslots.hpp" + +/***************************************************************************** +** Fuctions +*****************************************************************************/ +/** + * @cond DO_NOT_DOXYGEN + */ + +void g() { + std::cout << " This is standalone g()" << std::endl; +} +void h(int i) { + std::cout << " This is standalone g(int): " << i << std::endl; +} + +class A { +public: + void g() { + std::cout << " This is A::g()" << std::endl; + } + void h(int i) { + std::cout << " This is A::g(int): " << i << std::endl; + } +}; + +/** + * @endcond + */ + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + A a; + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* 1 Signal, 2 Slots" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + ecl::Signal<> sig_void; + ecl::Slot<> slot_void0(g); + ecl::Slot<> slot_void1(&A::g,a); + + sig_void.connect("void_test"); + slot_void0.connect("void_test"); + slot_void1.connect("void_test"); + std::cout << "Emitting:" << std::endl; + sig_void.emit(); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Statistics" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + ecl::SigSlotsManager<>::printStatistics(); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* 1 Data Signal, 2 Data Slots" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + ecl::Signal sig_data; + ecl::Slot slot_data0(h); + ecl::Slot slot_data1(&A::h,a); + + sig_data.connect("data_test"); + slot_data0.connect("data_test"); + slot_data1.connect("data_test"); + std::cout << "Emitting:" << std::endl; + sig_data.emit(3); + + std::cout << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << "* Statistics" << std::endl; + std::cout << "***************************************************************" << std::endl; + std::cout << std::endl; + + ecl::SigSlotsManager::printStatistics(); + + return 0; +} + diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_sigslots/src/test/CMakeLists.txt new file mode 100644 index 0000000..0a17378 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/test/CMakeLists.txt @@ -0,0 +1,20 @@ +############################################################################### +# Test Macro +############################################################################### + +macro(ecl_sigslots_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries( + ecl_test_${test_name} + ecl_config::ecl_config + ecl_threads::ecl_threads + ) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_sigslots_add_gtest(sigslots) diff --git a/ros2_ws/src/ecl_core/ecl_sigslots/src/test/sigslots.cpp b/ros2_ws/src/ecl_core/ecl_sigslots/src/test/sigslots.cpp new file mode 100644 index 0000000..f4d397f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_sigslots/src/test/sigslots.cpp @@ -0,0 +1,181 @@ +/** + * @file /ecl_sigslots/src/test/sigslots.cpp + * + * @brief Unit test the sigslots api. + * + * @date May 16, 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + + +#include +#include +#include +#include "../../include/ecl/sigslots/signal.hpp" +#include "../../include/ecl/sigslots/slot.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::Signal; +using ecl::Slot; + +/** + * @cond DO_NOT_DOXYGEN + */ +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace sigslots { +namespace tests { + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class A { +public: + A() : f_count(0), g_count(0) {} + + void f(const int &/*i*/) { +// std::cout << " Member function with argument: " << i << std::endl;; + f_count++; + } + void g() { + g_count++; +// std::cout << " Member function" << std::endl;; + } + int f_count, g_count; +}; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +static int f_count = 0; +static int g_count = 0; + +void f(const int &/*i*/) +{ + f_count++; +// std::cout << " Global function with argument: " << i << std::endl;; +} + +void g() +{ + g_count++; +// std::cout << " Global function" << std::endl;; +} + +} // namespace tests +} // namespace signals +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::sigslots::tests; + +/** + * @endcond + */ +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SigSlotsTests, voidSigSlots) { + + A a; + Signal<> sig_void; + + Slot<> slot_void0(g,"void_test"); + Slot<> slot_void1(&A::g,a); + + sig_void.connect("void_test"); +// slot_void0.connect("void_test"); + slot_void1.connect("void_test"); + + sig_void.emit(); + +// ecl::SigSlotsManager<>::printStatistics(); + +// std::cout << "a.g_count: " << a.g_count << std::endl; +// std::cout << "g_count: " << g_count << std::endl; + EXPECT_EQ(1,a.g_count); + EXPECT_EQ(1,g_count); +} + +TEST(SigSlotsTests, relay) { + + A a; + Signal<> sig_starter; + Signal<> sig_relay; + + Slot<> slot_relayed_goal(g); + + sig_starter.connect("relay"); + sig_relay.connectAsSlot("relay"); + sig_relay.connect("final_goal"); + slot_relayed_goal.connect("final_goal"); + + sig_starter.emit(); + +// std::cout << "g_count: " << g_count << std::endl; + EXPECT_EQ(2,g_count); +} + +TEST(SigSlotsTests,dataSigSlots) { + + A a; + Signal sig_int; + Slot slot_int0(f); + Slot slot_int1(&A::f,a); + + sig_int.connect("int_test"); + slot_int0.connect("int_test"); + slot_int1.connect("int_test"); + + sig_int.emit(4); +// std::cout << "a.f_count: " << a.f_count << std::endl; +// std::cout << "f_count: " << f_count << std::endl; + EXPECT_EQ(1,a.f_count); + EXPECT_EQ(1,f_count); +} + +TEST(SigSlotsTests, disconnect) { + + Signal<> signal; + Slot<> slot(g); + signal.connect("disconnect"); + slot.connect("disconnect"); + signal.emit(); + slot.disconnect(); + Signal data_signal; + Slot data_slot(f); + data_signal.connect("disconnect"); // Each data type has its own 'namespace' per se, so this doesn't clash with the above. + data_slot.connect("disconnect"); + data_signal.emit(1); + data_slot.disconnect(); + data_signal.emit(1); // Shouldn't increment + + EXPECT_EQ(3,g_count); + EXPECT_EQ(2,f_count); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_statistics/.cproject b/ros2_ws/src/ecl_core/ecl_statistics/.cproject new file mode 100644 index 0000000..a12c732 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/.cproject @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + tests + true + true + true + + + make + + clean + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/.project b/ros2_ws/src/ecl_core/ecl_statistics/.project new file mode 100644 index 0000000..7138aa8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/.project @@ -0,0 +1,78 @@ + + + ecl_statistics + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_statistics/CHANGELOG.rst new file mode 100644 index 0000000..b4b402c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/CHANGELOG.rst @@ -0,0 +1,7 @@ +========= +Changelog +========= + +0.61.15 (2016-11-09) +-------------------- +* Class added for computing cumulative means and variances diff --git a/ros2_ws/src/ecl_core/ecl_statistics/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/CMakeLists.txt new file mode 100644 index 0000000..a50f2d3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/CMakeLists.txt @@ -0,0 +1,57 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_statistics) + +############################################################################## +# ament +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. + +# Getting some confounding variadic warnings from Sophus, so turn isystem +# back on so this build hides those warnings. +# set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_linear_algebra REQUIRED) +find_package(ecl_mpl REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_linear_algebra + ecl_mpl + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_statistics/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_statistics/doxygen/mainpage.dox new file mode 100644 index 0000000..9d540b8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/doxygen/mainpage.dox @@ -0,0 +1,112 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This group mostly contains classes relevant to the probabilistics of mobile robot slam. + + Include the following at the top of any translation unit that requires the ecl + probabilistic tools. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Statistics Classes + using ecl::CovarianceEllipsoid; + using ecl::CovarianceEllipsoid2f; // also 2d, 3f, 3d typedef variants + @endcode + + You will also need to link to -lecl_statistics. + +\section usage Usage + + @subsection covarianceEllipses Covariance Ellipsoids + + +mplemented by the template class `CovarianceEllipsoid` - this takes two template parameters. The first is the float type used (usually `float`/`double`) and the second, the dimension of the ellipsoid to be determined. + +Specialisations are enabled for 2 and 3 dimensional types only as we haven't had a need to develop a general implementation. + +== Typedefs == + +Typedefs exist for the template class in the eigen style: + +{{{ +#!cplusplus +using ecl::CovarianceEllipsoid2f; +using ecl::CovarianceEllipsoid2d; +using ecl::CovarianceEllipsoid3f; +using ecl::CovarianceEllipsoid3d; +}}} + +== Usage == + +You typically feed the covariance ellipsoid with a positive definite symmetric matrix (eigen matrix). +Take care entering the positive definite symmetric matrix - the class does not yet do checking to +make sure it is positive definite symmetric. + +You can either input the matrix via the constructor - in which case it will automatically calculate +the ellipsoid properties, or pass it in later via the `compute()` method: + +@code +Matrix2d M; +M << 3.0, 1.0, 1.0, 5.0; // must be a positive definite, symmetric matrix + +CovarianceEllipsoid2d ellipse(M); + +// OR + +CovarianceEllipsoid2d ellipse; +ellipse.compute(M); +@endcode + +@code +Matrix2d M; +M << 3.0, 1.0, 1.0, 5.0; +CovarianceEllipsoid2d ellipse(M); + +// ellipse minor and major axis lengths +const Vector2d& lengths = ellipse.lengths(); +double eigen_value_0 = lengths[0]*lengths[0]; + +// angle between x-axis and major axis of the ellipse +double angle = ellipse.rotation(); + +// values of the intercepts of the ellipse with x and y axes +const Vector2d& intercepts = ellipse.intercepts(); + +// the ellipse axes/covariance eigenvectors as column vectors in a matrix +const Matrix2d& axes = ellipse.axes(); +@endcode + +The 3d version is similar, but will only calculate intercepts and axes respectively. +Note that the axes are sorted (to ensure a right-handed co-ordinate system) and normalised. + +@code +Matrix3d P; +double sigmaX(0.1); +double sigmaY(0.5); +double sigmaT(0.3); +P << sigmaX*sigmaX, 0, 0, 0, sigmaY*sigmaY, 0, 0, 0, sigmaT*sigmaT; +CovarianceEllipsoid3d ellipse(P); + +const Vector3d& lengths = ellipse.lengths(); +double eigen_value_0 = lengths[0]*lengths[0]; +const Matrix3d& axes = ellipse.axes(); +@endcode + +\section unitTests Unit Tests + + - src/test/covariance_ellipsoids.cpp + +\section ChangeLog + + - Jan 10 : 3d ellipses via the ecl::CovarianceEllipsoid solver. + - Nov 09 : 2d ellipses via the ecl::CovarianceEllipsoid solver. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_statistics/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_statistics/doxygen/namespaces.dox new file mode 100644 index 0000000..b1fda5c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/doxygen/namespaces.dox @@ -0,0 +1,7 @@ +** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..1a014cd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(statistics) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics.hpp b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics.hpp new file mode 100644 index 0000000..fbbc590 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics.hpp @@ -0,0 +1,24 @@ +/** + * @file /include/ecl/statistics.hpp + * + * @brief Various probabilistic classes mostly relevant to slam. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STATISTICS_HPP_ +#define ECL_STATISTICS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "statistics/covariance_ellipsoid.hpp" +#include "statistics/cumulative_statistics.hpp" + +#endif /* ECL_STATISTICS_HPP_ */ + + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/CMakeLists.txt new file mode 100644 index 0000000..413e456 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/statistics) + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/covariance_ellipsoid.hpp b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/covariance_ellipsoid.hpp new file mode 100644 index 0000000..1156f14 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/covariance_ellipsoid.hpp @@ -0,0 +1,542 @@ +/** + * @file /include/ecl/statistics/covariance_ellipsoid.hpp + * + * @brief Generates the ellipsoid for a multivariate guassian distribution. + * + * Generates the ellipsoid for a multivariate guassian distribution. + * + * Some of this code is adapted from the matlab script below. Note that we + * don't do mahalanobis distance conversions - haven't found a dire need + * for them yet - should do in the future? + * + * http://openslam.informatik.uni-freiburg.de/data/svn/tjtf/trunk/matlab/plotcov2.m + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STATISTICS_COVARIANCE_ELLIPSOID_HPP_ +#define ECL_STATISTICS_COVARIANCE_ELLIPSOID_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [CovarianceEllipsoid] +*****************************************************************************/ +/** + * @brief Parent template for covariance ellipsoids. + * + * Do not use this directly (yet). Use the specialisations instead. + * + * @sa CovarianceEllipsoid. + */ +template +class ECL_PUBLIC CovarianceEllipsoid { +private: + /** + * @brief Prevents usage of this template class directly. + * + * This class isn't yet intended for generic use - use the specialisations + * instead. + */ + CovarianceEllipsoid() {}; + virtual ~CovarianceEllipsoid() {}; +}; + +/***************************************************************************** +** Interface [CovarianceEllipsoid2f] +*****************************************************************************/ +/** + * @brief Specialisation of covariance ellipsoids in two dimensions. + * + * This creates ellipsoids for 2x2 covariance matrices, i.e. the usual + * sort for mobile robot navigation. It uses lovely dirty c-style code + * to work out the underlying eigen properties rather than Eigen's solver - + * tends to be a bit faster in only two dimensions. + * + * Usage: + * + * This class is also more conveniently typedef'd as CovarianceEllipsoid2f. + * + * You can either instantiate directly through the constructor or by + * hand via the compute() method. Recomputing is also possible without + * having to construct an entirely new instance. + * + * @code + * CovarianceEllipsoid2f ellipsoid(M); // OR + * CovarianceEllipsoid2f ellipsoid_hand; + * ellipsoid_hand.compute(M); + * @endcode + * + * Once generated, the ellipse properties can easily be extracted. + * + * @code + * Vector2f lengths = ellipsoid.lengths(); // axis lengths. + * float angle = ellipsoid.rotation(); // angle of rotation to the major axis + * @endcode + * + * There are a couple more methods that can be accessed for more detailed + * information about the ellipse, but the above two are usually sufficient + * for drawing your own ellipses. + * + * @sa CovarianceEllipsoid. + */ +template<> +class ECL_PUBLIC CovarianceEllipsoid { +public: + /** + * @brief Default constructor, use with compute(). + * + * This constructor does not do anything - you must use it together with the + * compute() function. Sometimes useful when using this class with containers. + */ + CovarianceEllipsoid(); + + /** + * @brief Automatically generates ellipsoid information at construction. + * + * Using the specified input covariance matrix, this constructor + * automatically generates (indirectly calls compute()) the full ellipse + * information, making it instantly ready for use. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + */ + CovarianceEllipsoid(const ecl::linear_algebra::Matrix2f& M); + + virtual ~CovarianceEllipsoid() {}; + + /** + * @brief Computes the covariance ellipsoid for the specified matrix. + * + * This can either be called indirectly via the constructor or directly + * via this function. In either case, it resets the object and generates/computes + * the resulting ellipse from the specified input covariance matrix. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + */ + void compute(const ecl::linear_algebra::Matrix2f& M); + + /** + * @brief Returns the precomputed ellipsoid minor/major axis lengths. + * + * Returns the precomputed ellipsoid minor/major axis lengths. + * + * @return Vector2d : the minor/major axis lengths. + */ + const ecl::linear_algebra::Vector2f& lengths() { return ellipse_lengths; } + /** + * @brief Returns the ellipse axes/covariance eigen vectors. + * + * This returns the ellipse axes (aka covariance eigen vectors) as + * columns of a matrix. + * @return Matrix2d : the set of eigenvectors as column vectors in a matrix. + */ + const ecl::linear_algebra::Matrix2f& axes() { return ellipse_axes; } + + /** + * @brief Calculates the rotation of the ellipse. + * + * This determines the angle between the x axis and the major axis + * of the ellipse. + * + * @return double : the rotation angle. + */ + double rotation(); + /** + * @brief Specifies the intercepts of the ellipse with the cartesian axes. + * + * This determines the distance from the origin to the ellipse boundary + * in the directions of the usual cartesian axes. Note that the intercepts + * here are given as a two dimensional vector and this is not the (x,y) + * pair of an intercept itself. + * + * Rather this is both the x and y magnitudes for which the full set of four + * intercepts can be generated. These magnitudes are the distances from + * the centre of the ellipse to the boundary of the ellipse in both the + * x and y directions. + * + * @return Vector2d : x and y-axis intercept distances from the origin. + */ + ecl::linear_algebra::Vector2f intercepts(); + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Vector2f ellipse_lengths; + ecl::linear_algebra::Matrix2f ellipse_axes; +}; + + + +/** + * @brief Specialisation of covariance ellipsoids in three dimensions. + * + * This creates ellipsoids for 3x3 covariance matrices, i.e. the usual + * sort for mobile robot navigation. It uses one of the eigen solvers. + * Currently it seems (we have not checked it thorougly yet) to correlate + * the order of eigenvalue-eigenvector pairs with the index of the matrix, + * which is good! + * + * Usage: + * + * This class is also more conveniently typedef'd as CovarianceEllipsoid3f. + * + * You can either instantiate directly through the constructor or by + * hand via the compute() method. Recomputing is also possible without + * having to construct an entirely new instance. + * + * @code + * CovarianceEllipsoid3f ellipsoid(M); // OR + * CovarianceEllipsoid3f ellipsoid_hand; + * ellipsoid_hand.compute(M); + * @endcode + * + * Once generated, the ellipse properties can easily be extracted. + * + * @code + * Vector3f lengths = ellipsoid.lengths(); // axis lengths. + * @endcode + * + * @sa CovarianceEllipsoid. + */ +template<> +class ECL_PUBLIC CovarianceEllipsoid { +public: + /** + * @brief Default constructor, use with compute(). + * + * This constructor does not do anything - you must use it together with the + * compute() function. Sometimes useful when using this class with containers. + */ + CovarianceEllipsoid(); + + /** + * @brief Automatically generates ellipsoid information at construction. + * + * Using the specified input covariance matrix, this constructor + * automatically generates (indirectly calls compute()) the full ellipse + * information, making it instantly ready for use. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + * @param sort : if true, ensure the resulting set is a right-hand configuration. + */ + CovarianceEllipsoid(const ecl::linear_algebra::Matrix3f& M, const bool sort = true); + + virtual ~CovarianceEllipsoid() {}; + + /** + * @brief Computes the covariance ellipsoid for the specified matrix. + * + * This can either be called indirectly via the constructor or directly + * via this function. In either case, it resets the object and generates/computes + * the resulting ellipse from the specified input covariance matrix. By default + * it will sort and normalise the resulting eigenvectors so that they form a + * right handed system. You can turn this off by setting the sort argument to + * false. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + * @param sort : if true, ensure the resulting set is a right-hand configuration. + */ + void compute(const ecl::linear_algebra::Matrix3f& M, const bool sort = true); + + /** + * @brief Returns the precomputed ellipsoid minor/major axis lengths. + * + * Returns the precomputed ellipsoid minor/major axis lengths. + * + * @return Vector2d : the minor/major axis lengths. + */ + const ecl::linear_algebra::Vector3f& lengths() { return ellipse_lengths; } + /** + * @brief Returns the ellipse axes/covariance eigen vectors. + * + * This returns the ellipse axes (aka covariance eigen vectors) as + * columns of a matrix. + * + * @return Matrix2d : the set of eigenvectors as column vectors in a matrix. + */ + const ecl::linear_algebra::Matrix3f& axes() { return ellipse_axes; } + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Vector3f ellipse_lengths; + ecl::linear_algebra::Matrix3f ellipse_axes; +}; + +/***************************************************************************** +** Interface [CovarianceEllipsoid2d] +*****************************************************************************/ +/** + * @brief Specialisation of covariance ellipsoids in two dimensions. + * + * This creates ellipsoids for 2x2 covariance matrices, i.e. the usual + * sort for mobile robot navigation. It uses lovely dirty c-style code + * to work out the underlying eigen properties rather than Eigen's solver - + * tends to be a bit faster in only two dimensions. + * + * Usage: + * + * This class is also more conveniently typedef'd as CovarianceEllipsoid2d. + * + * You can either instantiate directly through the constructor or by + * hand via the compute() method. Recomputing is also possible without + * having to construct an entirely new instance. + * + * @code + * CovarianceEllipsoid2d ellipsoid(M); // OR + * CovarianceEllipsoid2d ellipsoid_hand; + * ellipsoid_hand.compute(M); + * @endcode + * + * Once generated, the ellipse properties can easily be extracted. + * + * @code + * Vector2d lengths = ellipsoid.lengths(); // axis lengths. + * double angle = ellipsoid.rotation(); // angle of rotation to the major axis + * @endcode + * + * There are a couple more methods that can be accessed for more detailed + * information about the ellipse, but the above two are usually sufficient + * for drawing your own ellipses. + * + * @sa CovarianceEllipsoid. + */ +template<> +class ECL_PUBLIC CovarianceEllipsoid { +public: + /** + * @brief Default constructor, use with compute(). + * + * This constructor does not do anything - you must use it together with the + * compute() function. Sometimes useful when using this class with containers. + */ + CovarianceEllipsoid(); + + /** + * @brief Automatically generates ellipsoid information at construction. + * + * Using the specified input covariance matrix, this constructor + * automatically generates (indirectly calls compute()) the full ellipse + * information, making it instantly ready for use. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + */ + CovarianceEllipsoid(const ecl::linear_algebra::Matrix2d& M); + + virtual ~CovarianceEllipsoid() {}; + + /** + * @brief Computes the covariance ellipsoid for the specified matrix. + * + * This can either be called indirectly via the constructor or directly + * via this function. In either case, it resets the object and generates/computes + * the resulting ellipse from the specified input covariance matrix. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + */ + void compute(const ecl::linear_algebra::Matrix2d& M); + + /** + * @brief Returns the precomputed ellipsoid minor/major axis lengths. + * + * Returns the precomputed ellipsoid minor/major axis lengths. + * + * @return Vector2d : the minor/major axis lengths. + */ + const ecl::linear_algebra::Vector2d& lengths() { return ellipse_lengths; } + /** + * @brief Returns the ellipse axes/covariance eigen vectors. + * + * This returns the ellipse axes (aka covariance eigen vectors) as + * columns of a matrix. + * @return Matrix2d : the set of eigenvectors as column vectors in a matrix. + */ + const ecl::linear_algebra::Matrix2d& axes() { return ellipse_axes; } + + /** + * @brief Calculates the rotation of the ellipse. + * + * This determines the angle between the x axis and the major axis + * of the ellipse. + * + * @return double : the rotation angle. + */ + double rotation(); + /** + * @brief Specifies the intercepts of the ellipse with the cartesian axes. + * + * This determines the distance from the origin to the ellipse boundary + * in the directions of the usual cartesian axes. Note that the intercepts + * here are given as a two dimensional vector and this is not the (x,y) + * pair of an intercept itself. + * + * Rather this is both the x and y magnitudes for which the full set of four + * intercepts can be generated. These magnitudes are the distances from + * the centre of the ellipse to the boundary of the ellipse in both the + * x and y directions. + * + * @return Vector2d : x and y-axis intercept distances from the origin. + */ + ecl::linear_algebra::Vector2d intercepts(); + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Vector2d ellipse_lengths; + ecl::linear_algebra::Matrix2d ellipse_axes; +}; + + + +/** + * @brief Specialisation of covariance ellipsoids in three dimensions. + * + * This creates ellipsoids for 3x3 covariance matrices, i.e. the usual + * sort for mobile robot navigation. It uses one of the eigen solvers. + * Currently it seems (we have not checked it thorougly yet) to correlate + * the order of eigenvalue-eigenvector pairs with the index of the matrix, + * which is good! + * + * Usage: + * + * This class is also more conveniently typedef'd as CovarianceEllipsoid3d. + * + * You can either instantiate directly through the constructor or by + * hand via the compute() method. Recomputing is also possible without + * having to construct an entirely new instance. + * + * @code + * CovarianceEllipsoid3d ellipsoid(M); // OR + * CovarianceEllipsoid3d ellipsoid_hand; + * ellipsoid_hand.compute(M); + * @endcode + * + * Once generated, the ellipse properties can easily be extracted. + * + * @code + * Vector3d lengths = ellipsoid.lengths(); // axis lengths. + * @endcode + * + * @sa CovarianceEllipsoid. + */ +template<> +class ECL_PUBLIC CovarianceEllipsoid { +public: + /** + * @brief Default constructor, use with compute(). + * + * This constructor does not do anything - you must use it together with the + * compute() function. Sometimes useful when using this class with containers. + */ + CovarianceEllipsoid(); + + /** + * @brief Automatically generates ellipsoid information at construction. + * + * Using the specified input covariance matrix, this constructor + * automatically generates (indirectly calls compute()) the full ellipse + * information, making it instantly ready for use. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + * @param sort : if true, ensure the resulting set is a right-hand configuration. + */ + CovarianceEllipsoid(const ecl::linear_algebra::Matrix3d& M, const bool sort = true); + + virtual ~CovarianceEllipsoid() {}; + + /** + * @brief Computes the covariance ellipsoid for the specified matrix. + * + * This can either be called indirectly via the constructor or directly + * via this function. In either case, it resets the object and generates/computes + * the resulting ellipse from the specified input covariance matrix. By default + * it will sort and normalise the resulting eigenvectors so that they form a + * right handed system. You can turn this off by setting the sort argument to + * false. + * + * @param M : the input covariance matrix (must be symmetric positive definite). + * @param sort : if true, ensure the resulting set is a right-hand configuration. + */ + void compute(const ecl::linear_algebra::Matrix3d& M, const bool sort = true); + + /** + * @brief Returns the precomputed ellipsoid minor/major axis lengths. + * + * Returns the precomputed ellipsoid minor/major axis lengths. + * + * @return Vector2d : the minor/major axis lengths. + */ + const ecl::linear_algebra::Vector3d& lengths() { return ellipse_lengths; } + /** + * @brief Returns the ellipse axes/covariance eigen vectors. + * + * This returns the ellipse axes (aka covariance eigen vectors) as + * columns of a matrix. + * + * @return Matrix2d : the set of eigenvectors as column vectors in a matrix. + */ + const ecl::linear_algebra::Matrix3d& axes() { return ellipse_axes; } + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + +private: + ecl::linear_algebra::Vector3d ellipse_lengths; + ecl::linear_algebra::Matrix3d ellipse_axes; +}; + +/***************************************************************************** +** Convenience Typedefs +*****************************************************************************/ +/** + * @brief Convenience typedef for 2f covariance ellipsoids. + * + * Convenience typedef for 2f covariance ellipsoids. + * + * @sa ecl::CovarianceEllipsoid + */ +typedef CovarianceEllipsoid CovarianceEllipsoid2f; +/** + * @brief Convenience typedef for 2d covariance ellipsoids. + * + * Convenience typedef for 2d covariance ellipsoids. + * + * @sa ecl::CovarianceEllipsoid + */ +typedef CovarianceEllipsoid CovarianceEllipsoid2d; +/** + * @brief Convenience typedef for 3f covariance ellipsoids. + * + * Convenience typedef for 3f covariance ellipsoids. + * + * @sa ecl::CovarianceEllipsoid + */ +typedef CovarianceEllipsoid CovarianceEllipsoid3f; + +/** + * @brief Convenience typedef for 3d covariance ellipsoids. + * + * Convenience typedef for 3d covariance ellipsoids. + * + * @sa ecl::CovarianceEllipsoid + */ +typedef CovarianceEllipsoid CovarianceEllipsoid3d; + + +} // namespace ecl + +#endif /* ECL_STATISTICS_COVARIANCE_ELLIPSOID_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/cumulative_statistics.hpp b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/cumulative_statistics.hpp new file mode 100644 index 0000000..d45428b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/include/ecl/statistics/cumulative_statistics.hpp @@ -0,0 +1,103 @@ +/** + * @file /ecl_statistics/include/ecl/statistics/cumulative_statistics.hpp + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_statistics_CUMULATIVE_STATISTICS_HPP_ +#define ecl_statistics_CUMULATIVE_STATISTICS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ + +/** + * @brief Dummy parent class for Homogenous points. + * + * SFINAE trick to ensure that only floats are used for the template parameter. + * The real class is in the specialisation. + */ +template +class CumulativeStatistics : public ecl::FailedObject {}; + +/** + * Calculate cumulative mean and variance (i.e. without storage). + */ +template +class CumulativeStatistics >::type> { +public: + CumulativeStatistics(): number_of_data(0.0) {} + + void clear() { number_of_data = 0.0; } + + /** + * Catch the new data and update the cumulative calculations. + * + * TODO it uses a float as a counter to increase the longevity of the cumulative calculation, + * however it really ought to handle the number_of_data rolling over problem. + * + * @param x : new data + */ + void push_back(const T & x) + { + number_of_data++; + if(number_of_data == 1.0) + { + old_mean = new_mean = x; + old_variance = 0.0; + } + else + { + new_mean = old_mean + static_cast(x - old_mean) / static_cast(number_of_data); + new_variance = old_variance + static_cast(x - old_mean) * static_cast(x - new_mean); + + old_mean = new_mean; + old_variance = new_variance; + } + } + + /** + * Number of data used for statistics + * @return T + */ + T size() const { return static_cast(number_of_data); } + + /** + * @brief Current cumulative calculation of mean. + * @return T or 0.0 if there is not yet data. + */ + T mean() const { return (number_of_data > 0) ? new_mean : 0.0; } + + /** + * @brief Current cumulative calculation of variance. + * @return T or 0.0 if there is not yet data. + */ + T variance() const { return ((number_of_data > 1) ? new_variance / (number_of_data - 1) : 0.0); } + +private: + T number_of_data; + T old_mean, old_variance; + T new_mean, new_variance; +}; + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace ecl + +#endif /* ecl_statistics_CUMULATIVE_STATISTICS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_statistics/package.xml b/ros2_ws/src/ecl_core/ecl_statistics/package.xml new file mode 100644 index 0000000..3b55797 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/package.xml @@ -0,0 +1,40 @@ + + + ecl_statistics + 1.2.1 + + Common statistical structures and algorithms for control systems. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_statistics + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_linear_algebra + ecl_mpl + ecl_type_traits + + ecl_license + ecl_build + ecl_config + ecl_linear_algebra + ecl_mpl + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/src/CMakeLists.txt new file mode 100644 index 0000000..45123f3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/src/lib/CMakeLists.txt new file mode 100644 index 0000000..eb1e4e5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/lib/CMakeLists.txt @@ -0,0 +1,39 @@ +############################################################################### +# SOURCES +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# INSTALL +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_linear_algebra::ecl_linear_algebra + ecl_mpl::ecl_mpl + ecl_type_traits::ecl_type_traits +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/lib/covariance_ellipsoid.cpp b/ros2_ws/src/ecl_core/ecl_statistics/src/lib/covariance_ellipsoid.cpp new file mode 100644 index 0000000..81fdf9d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/lib/covariance_ellipsoid.cpp @@ -0,0 +1,299 @@ +/** + * @file /src/lib/covariance_ellipsoid.cpp + * + * @brief Implementation for covariance ellipsoids. + * + * @date November 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/statistics/covariance_ellipsoid.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::linear_algebra::Matrix2f; +using ecl::linear_algebra::Vector2f; +using ecl::linear_algebra::Matrix3f; +using ecl::linear_algebra::Vector3f; + +using ecl::linear_algebra::Matrix2d; +using ecl::linear_algebra::Vector2d; +using ecl::linear_algebra::Matrix3d; +using ecl::linear_algebra::Vector3d; + +/***************************************************************************** +** Implementation [CovarianceEllipsoid2f] +*****************************************************************************/ +CovarianceEllipsoid::CovarianceEllipsoid() : + ellipse_lengths(Vector2f::Ones()), + ellipse_axes(Matrix2f::Identity()) +{} + +CovarianceEllipsoid::CovarianceEllipsoid(const ecl::linear_algebra::Matrix2f &M) { + compute(M); +} +void CovarianceEllipsoid::compute(const ecl::linear_algebra::Matrix2f &M) { + + // CHECK: symmetricity of M + + /********************* + ** Eigenvalues + **********************/ + float a = M(0,0); + float b = M(0,1); + float c = M(1,0); + float d = M(1,1); + + float tmp = sqrtf((a+d)*(a+d)/4 - a*d + b*c); + ellipse_lengths << sqrtf((a+d)/2 + tmp), sqrtf((a+d)/2 - tmp); + + // CHECK: all ellipse_lengths are >= 0 (positive semi-definite check) + // CHECK: ordered in decreasing order of magnitude + + /********************* + ** Eigenvectors + **********************/ + if( c != 0 ) { + ellipse_axes(0,0) = ellipse_lengths(0)*ellipse_lengths(0)-d; + ellipse_axes(1,0) = c; + ellipse_axes(0,1) = ellipse_lengths(1)*ellipse_lengths(1)-d; + ellipse_axes(1,1) = c; + } else if( b != 0 ) { + ellipse_axes(0,0) = b; + ellipse_axes(1,0) = ellipse_lengths(0)*ellipse_lengths(0)-a; + ellipse_axes(0,1) = b; + ellipse_axes(1,1) = ellipse_lengths(1)*ellipse_lengths(1)-a; + } + else { + if ( a > d ) { + ellipse_axes << 1, 0, + 0, 1; + } else { + ellipse_axes << 0, 1, + 1, 0; + } + } + /********************* + ** Normalise Evectors + **********************/ + ellipse_axes.block<2,1>(0,0).normalize(); + ellipse_axes.block<2,1>(0,1).normalize(); +} + +double CovarianceEllipsoid::rotation() { + return atan2f(ellipse_axes(1,0), ellipse_axes(0,0)); +} + +Vector2f CovarianceEllipsoid::intercepts() { + + Vector2f intercept_magnitudes; + float t; + float angle = rotation(); + + /********************* + ** Parametric Form + **********************/ + // here t is a parameter and theta is the rotation angle + // + // x = lambda1 cos(t)cos(theta) - lambda2 sin(t)sin(theta) + // y = lambda1 cos(t)sin(theta) + lambda2 sin(t)cos(theta) + // + // To find the intersection with the x axis, set y = 0, then + // t = arctan[ - (lambda1/lambda2) tan(theta) ] + // To find the intersection with the y axis, set x = 0, then + // t = arctan[ (lambda1/lambda2) cot(theta) ] + + /********************* + ** X Axis + **********************/ + t = atan2f( -(ellipse_lengths(0)/ellipse_lengths(1))*tanf(angle), 1.0 ); + intercept_magnitudes(0) = fabsf(ellipse_lengths(0)*cosf(t)*cosf(angle) - ellipse_lengths(1)*sinf(t)*sinf(angle)); + /********************* + ** Y Axis + **********************/ + t = atan2f( (ellipse_lengths(0)/ellipse_lengths(1)), tanf(angle) ); // Could this get dodgy with tan going to infinity? + intercept_magnitudes(1) = fabsf(ellipse_lengths(0)*cosf(t)*sinf(angle) + ellipse_lengths(1)*sinf(t)*sinf(angle)); + + return intercept_magnitudes; +} + +/***************************************************************************** +** Implementation [CovarianceEllipsoid2d] +*****************************************************************************/ +CovarianceEllipsoid::CovarianceEllipsoid() : + ellipse_lengths(Vector2d::Ones()), + ellipse_axes(Matrix2d::Identity()) +{} + +CovarianceEllipsoid::CovarianceEllipsoid(const ecl::linear_algebra::Matrix2d &M) { + compute(M); +} +void CovarianceEllipsoid::compute(const ecl::linear_algebra::Matrix2d &M) { + + // CHECK: symmetricity of M + + /********************* + ** Eigenvalues + **********************/ + double a = M(0,0); + double b = M(0,1); + double c = M(1,0); + double d = M(1,1); + + double tmp = sqrt((a+d)*(a+d)/4 - a*d + b*c); + ellipse_lengths << sqrt((a+d)/2 + tmp), sqrt((a+d)/2 - tmp); + + // CHECK: all ellipse_lengths are >= 0 (positive semi-definite check) + // CHECK: ordered in decreasing order of magnitude + + /********************* + ** Eigenvectors + **********************/ + if( c != 0 ) { + ellipse_axes(0,0) = ellipse_lengths(0)*ellipse_lengths(0)-d; + ellipse_axes(1,0) = c; + ellipse_axes(0,1) = ellipse_lengths(1)*ellipse_lengths(1)-d; + ellipse_axes(1,1) = c; + } else if( b != 0 ) { + ellipse_axes(0,0) = b; + ellipse_axes(1,0) = ellipse_lengths(0)*ellipse_lengths(0)-a; + ellipse_axes(0,1) = b; + ellipse_axes(1,1) = ellipse_lengths(1)*ellipse_lengths(1)-a; + } + else { + if ( a > d ) { + ellipse_axes << 1, 0, + 0, 1; + } else { + ellipse_axes << 0, 1, + 1, 0; + } + } + /********************* + ** Normalise Evectors + **********************/ + ellipse_axes.block(0,0,2,1).normalize(); + ellipse_axes.block(0,1,2,1).normalize(); +} + +double CovarianceEllipsoid::rotation() { + return atan2(ellipse_axes(1,0), ellipse_axes(0,0)); +} + +Vector2d CovarianceEllipsoid::intercepts() { + + Vector2d intercept_magnitudes; + double t; + double angle = rotation(); + + /********************* + ** Parametric Form + **********************/ + // here t is a parameter and theta is the rotation angle + // + // x = lambda1 cos(t)cos(theta) - lambda2 sin(t)sin(theta) + // y = lambda1 cos(t)sin(theta) + lambda2 sin(t)cos(theta) + // + // To find the intersection with the x axis, set y = 0, then + // t = arctan[ - (lambda1/lambda2) tan(theta) ] + // To find the intersection with the y axis, set x = 0, then + // t = arctan[ (lambda1/lambda2) cot(theta) ] + + /********************* + ** X Axis + **********************/ + t = atan2( -(ellipse_lengths(0)/ellipse_lengths(1))*tan(angle), 1.0 ); + intercept_magnitudes(0) = fabs(ellipse_lengths(0)*cos(t)*cos(angle) - ellipse_lengths(1)*sin(t)*sin(angle)); + /********************* + ** Y Axis + **********************/ + t = atan2( (ellipse_lengths(0)/ellipse_lengths(1)), tan(angle) ); // Could this get dodgy with tan going to infinity? + intercept_magnitudes(1) = fabs(ellipse_lengths(0)*cos(t)*sin(angle) + ellipse_lengths(1)*sin(t)*sin(angle)); + + return intercept_magnitudes; +} + + + +/***************************************************************************** +** Implementation [CovarianceEllipsoid3f] +*****************************************************************************/ +CovarianceEllipsoid::CovarianceEllipsoid() : + ellipse_lengths(Vector3f::Ones()), + ellipse_axes(Matrix3f::Identity()) +{} + +CovarianceEllipsoid::CovarianceEllipsoid(const ecl::linear_algebra::Matrix3f &M, const bool sort) { + compute(M, sort); +} +void CovarianceEllipsoid::compute(const ecl::linear_algebra::Matrix3f &M, const bool sort) { + + Eigen::EigenSolver esolver(M); + + ellipse_lengths[0] = sqrtf(esolver.pseudoEigenvalueMatrix()(0,0)); + ellipse_lengths[1] = sqrtf(esolver.pseudoEigenvalueMatrix()(1,1)); + ellipse_lengths[2] = sqrtf(esolver.pseudoEigenvalueMatrix()(2,2)); + ellipse_axes = esolver.pseudoEigenvectors (); + + if ( sort ) { + // Note that sorting of eigenvalues may end up with left-hand coordinate system. + // So here we correctly sort it so that it does end up being righ-handed and normalised. + ecl::linear_algebra::Vector3f c0 = ellipse_axes.block<3,1>(0,0); c0.normalize(); + ecl::linear_algebra::Vector3f c1 = ellipse_axes.block<3,1>(0,1); c1.normalize(); + ecl::linear_algebra::Vector3f c2 = ellipse_axes.block<3,1>(0,2); c2.normalize(); + ecl::linear_algebra::Vector3f cc = c0.cross(c1); + if (cc.dot(c2) < 0) { + ellipse_axes << c1, c0, c2; + double e = ellipse_lengths[0]; ellipse_lengths[0] = ellipse_lengths[1]; ellipse_lengths[1] = e; + } else { + ellipse_axes << c0, c1, c2; + } + } +} + +CovarianceEllipsoid::CovarianceEllipsoid() : + ellipse_lengths(Vector3d::Ones()), + ellipse_axes(Matrix3d::Identity()) +{} + +CovarianceEllipsoid::CovarianceEllipsoid(const ecl::linear_algebra::Matrix3d &M, const bool sort) { + compute(M,sort); +} +void CovarianceEllipsoid::compute(const ecl::linear_algebra::Matrix3d &M, const bool sort) { + Eigen::EigenSolver esolver(M); + + ellipse_lengths[0] = sqrt(esolver.pseudoEigenvalueMatrix()(0,0)); + ellipse_lengths[1] = sqrt(esolver.pseudoEigenvalueMatrix()(1,1)); + ellipse_lengths[2] = sqrt(esolver.pseudoEigenvalueMatrix()(2,2)); + ellipse_axes = esolver.pseudoEigenvectors (); + + if ( sort ) { + // Note that sorting of eigenvalues may end up with left-hand coordinate system. + // So here we correctly sort it so that it does end up being righ-handed and normalised. + ecl::linear_algebra::Vector3d c0 = ellipse_axes.block<3,1>(0,0); c0.normalize(); + ecl::linear_algebra::Vector3d c1 = ellipse_axes.block<3,1>(0,1); c1.normalize(); + ecl::linear_algebra::Vector3d c2 = ellipse_axes.block<3,1>(0,2); c2.normalize(); + ecl::linear_algebra::Vector3d cc = c0.cross(c1); + if (cc.dot(c2) < 0) { + ellipse_axes << c1, c0, c2; + double e = ellipse_lengths[0]; ellipse_lengths[0] = ellipse_lengths[1]; ellipse_lengths[1] = e; + } else { + ellipse_axes << c0, c1, c2; + } + } +} + + +} // namespace ecl + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_statistics/src/test/CMakeLists.txt new file mode 100644 index 0000000..cac3048 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/test/CMakeLists.txt @@ -0,0 +1,17 @@ +############################################################################### +# GTest setup +############################################################################### + +macro(ecl_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# GTests +############################################################################### + +ecl_add_gtest(covariance_ellipsoids) +ecl_add_gtest(cumulative_statistics) diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/test/covariance_ellipsoids.cpp b/ros2_ws/src/ecl_core/ecl_statistics/src/test/covariance_ellipsoids.cpp new file mode 100644 index 0000000..1dec3e3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/test/covariance_ellipsoids.cpp @@ -0,0 +1,119 @@ +/** + * @file /src/test/covariance_ellipsoids.cpp + * + * @brief Unit Test for covariance ellipsoids. + * + * @date October 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/statistics/covariance_ellipsoid.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::CovarianceEllipsoid2d; +using ecl::CovarianceEllipsoid3d; +using ecl::linear_algebra::Matrix2d; +using ecl::linear_algebra::Vector2d; +using ecl::linear_algebra::Matrix3d; +using ecl::linear_algebra::Vector3d; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(CovarianceTests,ellipsoid2D) { + Matrix2d M; + M << 3.0, 1.0, 1.0, 5.0; // must be a positive definite, symmetric matrix +// M << 0.001801, -0.000047, -0.000047, 0.000259; +// M << 0.0000009661, 0.0000065, 0.0000065, 0.0001261; + + CovarianceEllipsoid2d ellipse(M); + const Vector2d& lengths = ellipse.lengths(); + double eigen_value_0 = lengths[0]*lengths[0]; + double angle = ellipse.rotation(); + const Vector2d& intercepts = ellipse.intercepts(); + const Matrix2d& axes = ellipse.axes(); + + EXPECT_GT(2.328,lengths[0]); EXPECT_LT(2.326,lengths[0]); + EXPECT_GT(5.415,eigen_value_0); EXPECT_LT(5.413,eigen_value_0); + EXPECT_GT(1.179,angle); EXPECT_LT(1.177,angle); + EXPECT_GT(1.674,intercepts[0]); EXPECT_LT(1.672,intercepts[0]); + EXPECT_GT(0.3828,axes(0,0)); EXPECT_LT(0.3826,axes(0,0)); + +// std::cout << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << " Covariance Ellipsoid2d" << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << std::endl; +// std::cout << "Test Matrix: " << std::endl; +// std::cout << std::endl; +// std::cout << M << std::endl; +// std::cout << std::endl; +// std::cout << "Axis Lengths: " << ellipse.lengths().transpose() << std::endl; +// std::cout << "Eigen Values: " << ellipse.lengths()(0)*ellipse.lengths()(0) << " " << ellipse.lengths()(1)*ellipse.lengths()(1) << std::endl; +// std::cout << "Axis Vectors: " << std::endl; +// std::cout << "Rotation angle: " << ellipse.rotation() << std::endl; +// std::cout << "Intercepts: " << ellipse.intercepts().transpose() << std::endl; +// std::cout << "Eigenvector Dot Product: " << ellipse.axes().block(0,0,2,1).transpose()*ellipse.axes().block(0,1,2,1) << std::endl; + +} + +TEST(CovarianceTests,ellipsoid3D) { + Matrix3d P; + double sigmaX(0.1); + double sigmaY(0.5); + double sigmaT(0.3); + P << sigmaX*sigmaX, 0, 0, 0, sigmaY*sigmaY, 0, 0, 0, sigmaT*sigmaT; + CovarianceEllipsoid3d ellipse(P); + + const Vector3d& lengths = ellipse.lengths(); + double eigen_value_0 = lengths[0]*lengths[0]; + const Matrix3d& axes = ellipse.axes(); + std::cout << axes << std::endl; + EXPECT_GT(0.101,lengths[0]); EXPECT_LT(0.099,lengths[0]); + EXPECT_GT(0.011,eigen_value_0); EXPECT_LT(0.009,eigen_value_0); + EXPECT_GT(1.001,axes(0,0)); EXPECT_LT(0.999,axes(0,0)); + +// std::cout << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << " Covariance Ellipsoid3d" << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << std::endl; +// std::cout << "Suppose we handle robot pose variances on sigmaX, sigmaY," << std::endl; +// std::cout << "sigmaT(heta)" << std::endl; +// std::cout << std::endl; +// std::cout << "[ sigmaX, sigmaY, sigmaT ]: [" << sigmaX << ", " << sigmaY << ", " << sigmaT << "]" << std::endl; +// std::cout << P << std::endl; +// std::cout << std::endl; +// std::cout << "Now we build covariance matrix: " << std::endl; +// std::cout << std::endl; +// std::cout << "Axis Lengths: " << ellipse.lengths().transpose() << std::endl; +// std::cout << "Eigen Values: " << ellipse.lengths()(0)*ellipse.lengths()(0) +// << " " << ellipse.lengths()(1)*ellipse.lengths()(1) +// << " " << ellipse.lengths()(2)*ellipse.lengths()(2) +// << std::endl; +// std::cout << "Axis Vectors: " << std::endl; +// std::cout << ellipse.axes() << std::endl; +// std::cout << std::endl; + +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_statistics/src/test/cumulative_statistics.cpp b/ros2_ws/src/ecl_core/ecl_statistics/src/test/cumulative_statistics.cpp new file mode 100644 index 0000000..7fba08d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_statistics/src/test/cumulative_statistics.cpp @@ -0,0 +1,62 @@ +/** + * @file /src/test/covariance_ellipsoids.cpp + * + * @brief Unit Test for covariance ellipsoids. + * + * @date October 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/statistics/cumulative_statistics.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(CumulativeStatistics, cumulative) { + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Cumulative Statistics" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + ecl::CumulativeStatistics statistics; + std::cout << "Size: " << statistics.size() << std::endl; + std::cout << " Mean: " << statistics.mean() << std::endl; + std::cout << " Variance: " << statistics.variance() << std::endl; + EXPECT_FLOAT_EQ(0.0, statistics.size()); + EXPECT_FLOAT_EQ(0.0, statistics.mean()); + EXPECT_FLOAT_EQ(0.0, statistics.variance()); + statistics.push_back(1.0); + std::cout << "Size: " << statistics.size() << std::endl; + std::cout << " Mean: " << statistics.mean() << std::endl; + std::cout << " Variance: " << statistics.variance() << std::endl; + EXPECT_FLOAT_EQ(1.0, statistics.size()); + EXPECT_FLOAT_EQ(1.0, statistics.mean()); + EXPECT_FLOAT_EQ(0.0, statistics.variance()); + statistics.push_back(2.0); + statistics.push_back(3.0); + statistics.push_back(4.0); + statistics.push_back(5.0); + std::cout << "Size: " << statistics.size() << std::endl; + std::cout << " Mean: " << statistics.mean() << std::endl; + std::cout << " Variance: " << statistics.variance() << std::endl; + EXPECT_FLOAT_EQ(5.0, statistics.size()); + EXPECT_FLOAT_EQ(3.0, statistics.mean()); + EXPECT_FLOAT_EQ(2.5, statistics.variance()); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_streams/.cproject b/ros2_ws/src/ecl_core/ecl_streams/.cproject new file mode 100644 index 0000000..0ed8446 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/.cproject @@ -0,0 +1,352 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + all + true + true + true + + + make + clean + true + true + true + + + make + test + true + true + true + + + make + tests + true + true + true + + + make + install + true + true + true + + + make + + examples + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_streams/.gitignore b/ros2_ws/src/ecl_core/ecl_streams/.gitignore new file mode 100644 index 0000000..ace6f68 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/.gitignore @@ -0,0 +1 @@ +dude_stream.txt diff --git a/ros2_ws/src/ecl_core/ecl_streams/.project b/ros2_ws/src/ecl_core/ecl_streams/.project new file mode 100644 index 0000000..4ae49c6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/.project @@ -0,0 +1,78 @@ + + + ecl_streams + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_streams/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_streams/CHANGELOG.rst new file mode 100644 index 0000000..75d9b33 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/CHANGELOG.rst @@ -0,0 +1,13 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_streams +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +1.0.6 (2020-01-11) +------------------ +* bugfix a warning-as-error on a throw in a method declaration`#99 `_ + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_streams/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/CMakeLists.txt new file mode 100644 index 0000000..0dc75b1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/CMakeLists.txt @@ -0,0 +1,59 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_streams) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_concepts REQUIRED) +find_package(ecl_converters REQUIRED) +find_package(ecl_devices REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_threads REQUIRED) # only required for demos +find_package(ecl_time REQUIRED) +find_package(ecl_type_traits REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_concepts + ecl_converters + ecl_devices + ecl_errors + ecl_time + ecl_type_traits +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_streams/doxygen/changelog.dox b/ros2_ws/src/ecl_core/ecl_streams/doxygen/changelog.dox new file mode 100644 index 0000000..e9b2421 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/doxygen/changelog.dox @@ -0,0 +1,21 @@ +/** + @page changelog ChangeLog + + @section Changes + + - Apr 10 : Now using ecl error handlers, optional exceptions and public/private compilation. + - Jan 10 : Convenience handle for @ref ecl::SocketClientStream "socket client" streams (also SocketServerStream). + - Dec 09 : @ref ecl::StringStream "String streaming" with a virtual device buffer. + - Dec 09 : @ref ecl::LogStream "LogStream" : multi-threaded, multi-mode log streams. + - Dec 09 : @ref ecl::SharedFileStream "SharedFileStream" : convenience handle for shared file streams. + - Nov 09 : Definition for the @ref ecl::ClearScreen "clrscr" manipulator. + - Nov 09 : Definition for the @ref ecl::EndOfLine "endl" manipulator. + - Nov 09 : Parent template for stream @ref ecl::Manipulator "manipulators". + - Nov 09 : Convenience handle for @ref ecl::SerialStream "SerialStream" "serial streams". + - Nov 09 : Convenience handle for output @ref ecl::OFileStream "file streams". + - Nov 09 : Convenience handle for a @ref ecl::EConsoleStream "standard error" stream. + - Nov 09 : Convenience handle for a @ref ecl::IConsoleStream "standard input" stream. + - Nov 09 : Convenience handle for a @ref ecl::OConsoleStream "standard output" stream. + - Nov 09 : Generic @ref ecl::TextStream "input-output" streaming from ecl devices. + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_streams/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_streams/doxygen/mainpage.dox new file mode 100644 index 0000000..a2595a9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/doxygen/mainpage.dox @@ -0,0 +1,254 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Streams provide a standardised c++ interface for connecting to + ecl input-output devices. + + - speed : control cannot afford serious slowdowns for convenience. + - extensible : must be able to create new devices easily. + - streams : all devices should connect in a standardised way to streams. + +@section otherStreamLibraries Comparison + + Finding a library with a standard/extensible interface that + works across devices and implements streaming operators is + like trying to find the pot at the bottom of the rainbow. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Templatised all purpose stream + using ecl::TextStream; + + // Convenience stream handles + using ecl::IConsoleStream; + using ecl::OConsoleStream; + using ecl::EConsoleStream; + using ecl::OFileStream; + using ecl::SerialStream; + using ecl::SharedFileStream; + using ecl::SocketClientStream; + using ecl::SocketServerStream; + using ecl::StringStream; + + // Special customised streams + using ecl::LogStream; + + // Stream manipulators + using ecl::endl; + using ecl::clrscr; + + @endcode + + You will also need to link to -lecl_streams. + +\section usage Usage + + @subsection openClose Initialisation + + Each stream-device pair can be instantiated via the generic TextStream object and the + underlying device opened via the device() member method. For example, + + @code + TextStream stream; + stream.device().open("dude.txt",New); + @endcode + + The console device is a special case - it is automatically opened. + + @subsection convenienceHandles Convenience Classes + +The preferred method of instantiation is via the constructor in the convenience classes. The +convenience classes are specialised interfaces that inherit from the appropriate Textstream +type (dependant on the template parameter). Examples, SerialStream, OFileStream. Rather than +calling stream.device().open(...) directly, you can use their constructors to instantiate +the stream. They are also more convenient than typing out template parameters continuously. + + + @code + OFileStream stream("dude.txt",New); + @endcode + + @subsection outputStreams Output Streams + + Output streams function similarly to the familiar cout stream. The primary advantage being that + they can easily be attached to any standard ecl io device. They can also be used with the + ecl_formatter classes. + + @code + OFileStream ostream; + Format format; format.width(5); format.precision(2); + double d = 1.0/3.0; + ostream << format(d); // This will send 0.33 to the stream. + ostream.flush(); + @endcode + + @subsection inputStreams Input Streams + + There are three ways to utilise an input stream: + + - reading element by element (separated by whitespace or newlines). + - reading raw characters (you must call enableRawCharReads()). + - reading line by line (not yet enabled). + + The first method is similar to the familiar cin, it will take a string and convert it to the requested type. + + @code + IConsoleStream istream; + double d; + istream >> d; + @endcode + + The second method is sometimes useful when communicated with raw character devices (e.g. a serial line). In + this situation, you must simply make use of the char input operator. + + @code + SerialStream serial_stream; + char c; + if ( serial_stream.device().remaining() ) { + serial_stream >> c; + } + @endcode + + The third method has not yet been implemented. + + @subsection logstreams Logging Streams + + @ref ecl::LogStream "LogStreams" are a convenient, fast means to + logging from multiple threads with multiple customisable modes. They can + also optionally automatically insert header and timestamp information. + + Multiple modes are most conveniently utilsed via customised enums. For example: + + @code + enum LogModes { + Warning, + Error, + Debug, + }; + @endcode + + Note that this is an advantage over alot of other loggers in that it gives you + the freedom to define your own error logging levels. Each mode can then be + associated inside the log stream with its own customised header. + + @code + LogStream log_stream("test.log") + log_stream.enableMode(Warning,"WARNING"); + log_stream.enableMode(Error,"ERROR"); + log_stream.enableMode(Debug,"DEBUG"); + @endcode + + This process can be repeated from multiple threads each with its own instance + of the log stream attached to the single file. Using the log stream is then + done via the macros LOG and FLUSH + + @code + LOG(log_stream, Warning) << "This is a log message from main().\n"; + FLUSH(log_stream) + @endcode + + By default this will automatically add header and timestamp information. You + can manually disable these if you prefer. + + +@section errorChecking Error Checking + + Output streams can generate errors that are not so easily checked compared with handling devices directly. + To check for failure, ecl streams use a mechanism similar to that of the standard cout stream. + + @code + ostream << 32.1; + if ( ostream.fail() ) { + std::cout << ostream.errorStatus().what() << std::endl; + } + @endcode + +@section Manipulators + + ECL manipulators are defined to enable some similar functionality to c++'s cout manipulators. + However they extend the concept to use class instantiations rather than functions. This + provides one important advantage over the former, these manipulators can retain state. Given + that they're also easy to customise, this opens up many possibilities. + + The default manipulators defined in the ecl export a few global instantiations, + namely + + - ecl::endl + - ecl::clrscr + + Using manipulators follows the same pattern as for standard c++ style cout manipulators. + + @code + int main() { + ecl::OConsoleStream ostream; + ostream << ecl::clrscr; + ostream << "Dude" << ecl::endl; + return; + } + @endcode + + Creating your own Manipulators: + + Any manipulator that you wish to define must inherit from this + parent class in the following manner: + + @code + include + + class MyManipulator : public ecl::Manipulator { + template + void action (OutputStream& ostream) { + // ... + } + }; + @endcode + +@section Benchmarking + + The following results are for streaming/flushing a large number of strings/floats + to various devices/streams. It was performed on a 32 bit single core intel processor + running linux (kernel 2.6.31) (exact values aren't important, rather the relative + differences). + + @code + Writing Char Strings: + OFile write : 58806 ns + SharedFile write : 47562 ns + OFile stream : 61739 ns + LogStream : 73753 ns + C++ ofstream : 83321 ns + Streaming Floats: + OFileStream : 693593 ns + Log stream : 711753 ns + C++ ofstream : 862120 ns + @endcode + +\section unitTests Unit Tests + + - src/test/file_streams.cpp + - src/test/string_streams.cpp + +\section demos Demos + + - src/examples/console_streams.cpp + - src/examples/log_streams.cpp + +\section utilities Utilities + + - ecl_core_apps/src/benchmarks/streams.cpp + - ecl_core_apps/src/benchmarks/files.cpp + +\section ChangeLog + + - @ref changelog "ChangeLog" + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_streams/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_streams/doxygen/namespaces.dox new file mode 100644 index 0000000..e1e1425 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/doxygen/namespaces.dox @@ -0,0 +1,17 @@ +/** + * @namespace ecl::streams + * + * @brief Streaming to and from input-output devices. + * + * Defines two generic streaming classes, TextStream and DataStream that can be connected to + * an input-output device. There is also a default implementation for TextStream which connects + * it to the standard output device. + **/ +/** + * @namespace ecl::streams::Interfaces + * + * @brief Streaming interfaces. + * + * These interfaces aren't used directly, but are brought into the streaming classes via + * mix-ins chosen by the type of device (input/output/both) they are connected to. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..1673413 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(streams) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams.hpp new file mode 100644 index 0000000..bf625b2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams.hpp @@ -0,0 +1,32 @@ +/** + * @file /include/ecl/streams.hpp + * + * @brief C++ style streams for ecl devices. + * + * C++ style streams for ecl devices. + * + * @date September, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IO_DEVICES_STREAMS_HPP_ +#define ECL_IO_DEVICES_STREAMS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "streams/text_stream.hpp" +#include "streams/console_streams.hpp" +#include "streams/file_streams.hpp" +#include "streams/log_stream.hpp" +#include "streams/serial_stream.hpp" +#include "streams/shared_file_stream.hpp" +#include "streams/socket_streams.hpp" +#include "streams/string_stream.hpp" +#include "streams/manipulators.hpp" + + +#endif /* ECL_IO_DEVICES_STREAMS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/CMakeLists.txt new file mode 100644 index 0000000..5d09709 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/CMakeLists.txt @@ -0,0 +1,15 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(manipulators) +add_subdirectory(text_streams) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/streams) + diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/console_streams.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/console_streams.hpp new file mode 100644 index 0000000..dfd2bdd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/console_streams.hpp @@ -0,0 +1,94 @@ +/** + * @file /include/ecl/streams/console_streams.hpp + * + * @brief Convenience handles for console textstreams. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_CONSOLE_STREAM_HPP_ +#define ECL_STREAMS_CONSOLE_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "text_stream.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Typedefs +*****************************************************************************/ +/** + * @brief Streams to standard output. + * + * This class operates similar to, but posesses several advantages to the + * usual cout c++ mechanism. + * + * - Faster. + * - Can be instantiated separately, each with its own internal buffer. + * + * The ecl could provide a global mechanism very much like the cout handle, + * but instantiating separately stops getting standard output messages + * confused and is a useful property for multi-threaded + * control applications. If you wish to use a global mechanism, simply + * instantiate a global instance in your program. + * + * Usage: + * + * There is no need to open this device, it automatically connects to + * stdout. + * @code + * OConsoleStream ostream; + * ostream << "Hey dude"; + * ostream.flush(); + * @endcode + * + * @sa @ref ecl::TextStream "TextStream". + */ +typedef TextStream OConsoleStream; +/** + * @brief Streams to standard input. + * + * Streams to standard input. + * + * Usage: + * + * There is no need to open this device, it automatically connects to + * stdin. + * @code + * IConsoleStream istream; + * string str; + * istream << str; + * @endcode + */ +typedef TextStream IConsoleStream; +/** + * @brief Streams to standard error. + * + * Streams to standard error. + * + * Usage: + * + * There is no need to open this device, it automatically connects to + * stderr. + * @code + * EConsoleStream estream; + * estream << "Boom"; + * estream.flush(); + * @endcode + */ +typedef TextStream EConsoleStream; + +} // namespace ecl + +#endif /* ECL_STREAMS_CONSOLE_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/file_streams.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/file_streams.hpp new file mode 100644 index 0000000..889d01e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/file_streams.hpp @@ -0,0 +1,78 @@ +/** + * @file /include/ecl/streams/file_streams.hpp + * + * @brief Convenience handles for file textstreams. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_FILE_STREAM_HPP_ +#define ECL_STREAMS_FILE_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "text_stream.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces [OFileStream] +*****************************************************************************/ +/** + * @brief Convenience class for OFile TextStream definitions. + * + * This class provides a convenient handle for both writing and + * opening TextStream objects. It has no further functionality. + * + * @sa @ref ecl::TextStream "TextStream". + */ +class ecl_streams_PUBLIC OFileStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the device manually via device().open() as you would do + * if using a TextStream. + */ + OFileStream() {}; + + /** + * @brief Convenience constructor for output file text streams. + * + * This constructor enables RAII style construction of the underlying + * device (this makes it distinct from a generic TextStream object). + * + * @param file_name : output file name. + * @param mode : mode for writing (New, Append). + * + * @exception StandardException : throws if the connection failed to open. + */ + OFileStream(const std::string &file_name, const WriteMode &mode = New) { + ecl_try { + if( !this->device().open(file_name, mode) ) { + error = this->device().error(); + } + } ecl_catch(StandardException &e) { + ecl_throw(StandardException(LOC,e)); + } + } + + virtual ~OFileStream() {}; +}; + +} // namespace ecl + +#endif /* ECL_STREAMS_FILE_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/log_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/log_stream.hpp new file mode 100644 index 0000000..b35a29b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/log_stream.hpp @@ -0,0 +1,228 @@ +/** + * @file /include/ecl/streams/log_stream.hpp + * + * @brief Macro enabled, fast logging stream. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_LOG_STREAM_HPP_ +#define ECL_STREAMS_LOG_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "text_stream.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Macros +*****************************************************************************/ + +/** + * @brief Enables log streaming. + * + * @ingroup Macros + * + * Simply use this alongside LogStream's << operator - it will provide the usual + * text stream functionality, but additionally provides the ability to + * insert header/timestamp information automatically into the beginning of the stream. + * + * @sa @ref ecl::LogStream "LogStream". + */ +#define LOG(logStream,mode) \ + if ( !logStream.isModeEnabled(mode) ) {} \ + else logStream.log(mode) // << rest of stream input will fill out here + +/** + * @brief Enables flushing of log streams. + * + * @ingroup Macros + * + * Use this with LOG and LogStream to flush the stream to the shared file. + * + * @sa @ref ecl::LogStream "LogStream". + */ +#define FLUSH(logStream) \ + if ( !logStream.isEnabled() ) {} \ + else { logStream.flush(); } + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [LogStream] +*****************************************************************************/ +/** + * @brief A customised textstream for fast, multithreaded logging to file. + * + * Together with the LOG and FLUSH macros, this class enables fast, + * multithreaded logging with multiple modes, customisable headers and timestamps. + * + * Usage: + * + * Multiple modes are most conveniently utilsed via customised enums. For example: + * + * @code + * enum LogModes { + * Warning, + * Error, + * Debug, + * }; + * @endcode + * + * Note that this is an advantage over alot of other loggers in that it gives you + * the freedom to define your own error logging levels. Each mode can then be + * associated inside the log stream with its own customised header. + * + * @code + * LogStream log_stream("test.log") + * log_stream.enableMode(Warning,"WARNING"); + * log_stream.enableMode(Error,"ERROR"); + * log_stream.enableMode(Debug,"DEBUG"); + * @endcode + * + * This process can be repeated from multiple threads each with its own instance + * of the log stream attached to the single file. Using the log stream is then + * done via the macros LOG and FLUSH + * + * @code + * LOG(log_stream, Warning) << "This is a log message from main().\n"; + * FLUSH(log_stream) + * @endcode + * + * By default this will automatically add header and timestamp information. You + * can manually disable these if you prefer. + */ +class ecl_streams_PUBLIC LogStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the underlying shared file device manually + * via device().open() as you would do if using a TextStream. + */ + LogStream() {}; + /** + * @brief Convenience constructor for logstreams. + * + * This constructor enables RAII style construction of the underlying + * shared file device. + * + * @param file_name : output file name. + * @param mode : mode for writing (New, Append). + * + * @exception StandardException : throws if the connection failed to open. + */ + LogStream(const std::string &file_name, const WriteMode &mode = New) : + write_header(true), + write_stamp(true) + { + ecl_try { + if ( !this->device().open(file_name, mode) ) { + error = this->device().error(); + } + } ecl_catch(StandardException &e) { + ecl_throw(StandardException(LOC,e)); + } + } + + virtual ~LogStream() {}; + + /** + * @brief Enable header information. + * + * This prints the header at the beginning of any logging message. The header is + * a string that is specified when calling the enableMode() function. + **/ + void enableHeader(); + /** + * @brief Disables header information. + * + * This turns off printing of the header at the beginning of any logging message. + **/ + void disableHeader(); + /** + * @brief Enable time stamps. + * + * This prints a timestamp at the beginning of any logging message. The timestamp + * is in the format seconds.nanoseconds (think unix time). + **/ + void enableTimeStamp(); + /** + * @brief Disable time stamps. + * + * This disables timestamps at the beginning of any logging message. The timestamp + * is in the format seconds.nanoseconds (think unix time). + **/ + void disableTimeStamp(); + + /** + * @brief Enable the given mode and associate the specified header. + * + * Enable the given log mode and associate it with the specified header string. + * @param mode : the log mode. + * @param header : the string to precede the log message if required. + **/ + void enableMode(int mode, const std::string header = ""); + /** + * @brief Disable the given log mode. + * + * Disable the given log mode. + * @param mode : the log mode. + **/ + void disableMode(int mode); + /** + * @brief Check to see if any modes are enabled. + * + * Check to see if any modes are enabled. + * @return bool : true if any modes are enabled, false otherwise. + **/ + bool isEnabled(); + /** + * @brief Check to see if a particular mode is enabled. + * + * Check to see if the specified mode is enabled. + * @return bool : true if the modes is enabled, false otherwise. + **/ + bool isModeEnabled(int mode); + /** + * @brief Log streaming function. + * + * Do not use this directly, rather it is indirectly utilised by + * the LOG macro, which should only reach here once isModeEnabled() is checked. + * It adds a header and timestamp if it is configured to do so and then passes the + * stream to the program for further additions. + * + * @param mode : log mode that is being logged. + * + * @return OutputTextStream : log stream's output streaming parent. + **/ + LogStream& log(int mode); + + using TextStream::operator<<; + +private: + bool write_header; + bool write_stamp; + std::map modes; + TimeStamp timestamp; + +}; + +} // namespace ecl + +#endif /* ECL_STREAMS_LOG_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/macros.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/macros.hpp new file mode 100644 index 0000000..7fb751c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/streams/macros.hpp + * + * @brief Macros for ecl streams. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_MACROS_HPP_ +#define ECL_STREAMS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_streams_EXPORTS // we are building a shared lib/dll + #define ecl_streams_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_streams_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_streams_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_streams_PUBLIC + #define ecl_streams_LOCAL +#endif + +#endif /* ECL_STREAMS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators.hpp new file mode 100644 index 0000000..2dd97f9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/streams/manipulators.hpp + * + * @brief Simple manipulators that operate on text streams. + * + * Simple manipulators that operate on text streams. The most common + * example is the endl manipulator. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_MANIPULATORS_HPP_ +#define ECL_STREAMS_MANIPULATORS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "manipulators/manipulator.hpp" +#include "text_stream.hpp" +#include "manipulators/end_of_line.hpp" +#include "manipulators/clear_screen.hpp" + +#endif /* ECL_STREAMS_MANIPULATORS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/CMakeLists.txt new file mode 100644 index 0000000..e689719 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/streams/manipulators) + diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/clear_screen.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/clear_screen.hpp new file mode 100644 index 0000000..91b3b6e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/clear_screen.hpp @@ -0,0 +1,81 @@ +/** + * @file /include/ecl/streams/manipulators/clear_screen.hpp + * + * @brief Really crude hack to clear the screen. + * + * Clears the screen just by spamming new lines at it - really crude! But + * at least it avoids any platform specific code. + * + * @date Dec 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_CLEAR_SCREEN_HPP_ +#define ECL_STREAMS_CLEAR_SCREEN_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../manipulators.hpp" +#include "../text_stream.hpp" +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [ClearScreen] +*****************************************************************************/ +/** + * @brief Manipulator that clears a terminal screen the c++ (hard) way. + * + * Function object manipulator that clears an output terminal + * screen the hard (c++) way by sending 80 new lines to it. + * + * The library instantiates a variable of this class under + * the name 'clrscr', so you need only refer to ecl::streams::clrscr to + * directly use it with your streams. + * + * @sa Manipulator. + **/ +class ecl_streams_PUBLIC ClearScreen : public Manipulator { +public: + /** + * @brief Clears a terminal screen the c++ (hard) way. + * + * Not very fast on most systems - hammers the terminal + * with alot of newlines. In windows this causes a problem since + * terminal screens are so slow and on screens with large + * resolutions, the 80 lines is not enough. Might actually + * implement system specific code for this at some time in the future. + * + * @tparam OutputStream : the output stream type. + * + * @param ostream : the stream to use for manipulation. + */ + template + void action (interfaces::OutputTextStream& ostream) { + for (int i = 0; i < 80; ++i ) { + ostream << "\n"; + } + } + virtual ~ClearScreen() {} +}; + +/***************************************************************************** +** Global Variables +*****************************************************************************/ + +extern ClearScreen clrscr; + +} // namespace ecl + + +#endif /* ECL_STREAMS_CLEAR_SCREEN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/end_of_line.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/end_of_line.hpp new file mode 100644 index 0000000..126aa18 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/end_of_line.hpp @@ -0,0 +1,71 @@ +/** + * @file /include/ecl/streams/manipulators/end_of_line.hpp + * + * @brief The familiar end of line manipulator, but as a c++ class. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_END_OF_LINE_HPP_ +#define ECL_STREAMS_END_OF_LINE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../manipulators.hpp" +#include "../text_stream.hpp" +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [EndOfLine] +*****************************************************************************/ +/** + * @brief Replicates the well known end of line/flush combination. + * + * This replicates the well known std::endl function as an ecl class based + * manipulator. The library instantiates a variable of this class under + * the name 'endl', so you need only refer to ecl::streams::endl to + * directly use it with your streams. + * + * @sa Manipulator. + */ +class ecl_streams_PUBLIC EndOfLine : public Manipulator { +public: + /** + * @brief Forces an end of line character/flush combination. + * + * Forces an end of line character/flush combination. + * + * @tparam OutputStream : the output stream type. + * + * @param ostream : the stream to use for manipulation. + */ + template + void action (interfaces::OutputTextStream& ostream) { + ostream << "\n"; + ostream.flush(); + } + + virtual ~EndOfLine() {} +}; + +/***************************************************************************** +** Global Variables +*****************************************************************************/ + +extern EndOfLine endl; + +} // namespace ecl + +#endif /* ECL_STREAMS_END_OF_LINE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/manipulator.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/manipulator.hpp new file mode 100644 index 0000000..620537e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/manipulators/manipulator.hpp @@ -0,0 +1,119 @@ +/** + * @file /include/ecl/streams/manipulators/manipulator.hpp + * + * @brief Parent template definition for stream manipulators. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_MANIPULATOR_HPP_ +#define ECL_STREAMS_MANIPULATOR_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Forwarding +*****************************************************************************/ + +namespace interfaces { + template class ECL_PUBLIC OutputTextStream; +} + +/***************************************************************************** +** Interface [Manipulator] +*****************************************************************************/ +/** + * @brief Parent template for c++ style stream manipulators. + * + * This class uses a trick embedded within the curiously recurring template + * method to allow static inheritance (important in this case because + * the manipulator function call is template based). + * Manipulators have an advantage over the usual c++ style manipulators in + * that they are themselves classes (not functions such as std::endl). This + * means that they can retain state from one insertion to the next. + * + * Usage: + * + * The manipulators defined in the ecl export a few global instantiations, + * namely + * + * - ecl::endl + * - ecl::clrscr + * + * Using them follows the same pattern as for standard c++ style cout manipulators. + * + * @code + * using ecl::streams::OConsoleStream; + * using ecl::streams::endl; + * int main() { + * OConsoleStream ostream; + * ostream << clrscr; + * ostream << "Dude" << endl; + * return; + * } + * @endcode + * + * Creating your own Manipulators: + * + * Any manipulator that you wish to define must inherit from this + * parent class in the following manner: + * + * @code + * include + * + * class MyManipulator : public ecl::Manipulator { + * template + * void action (OutputStream& ostream) { + * // ... + * } + * }; + * @endcode + * + * @tparam Derived : the child manipulator the crtp uses. + * + * @sa Manipulator. + */ +template +class ecl_streams_PUBLIC Manipulator { +public: + /** + * @brief The static crtp virtual parent call. + * + * This is exactly like a virtual function in a non-template c++ + * parent class, except it works for templates in the derived type. + * This function calls the derived class' action() method with + * the same signature. + * + * @param ostream : the stream to use for manipulation. + * + * @tparam OutputStream : the output stream type. + * + * @sa Manipulator. + */ + template + void insert (interfaces::OutputTextStream& ostream) { + ecl_compile_time_concept_check(OutputCharDeviceConcept); + static_cast(this)->action(ostream); + } + + virtual ~Manipulator() {} +}; + +} // namespace ecl + +#endif /* ECL_STREAMS_MANIPULATOR_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/serial_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/serial_stream.hpp new file mode 100644 index 0000000..327f825 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/serial_stream.hpp @@ -0,0 +1,84 @@ +/** + * @file /include/ecl/streams/serial_stream.hpp + * + * @brief Convenience handle for serial textstreams. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_SERIAL_STREAM_HPP_ +#define ECL_STREAMS_SERIAL_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "text_stream.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces [SerialStream] +*****************************************************************************/ +/** + * @brief Convenience class for Serial TextStream definitions. + * + * This class provides a convenient handle for both writing and + * opening TextStream objects. It has no further functionality. + * + * @sa @ref ecl::TextStream "TextStream". + */ +class ecl_streams_PUBLIC SerialStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the device manually via device().open() as you would do + * if using a TextStream. + */ + SerialStream() {}; + /** + * @brief Convenience constructor for serial text streams. + * + * This constructor enables RAII style construction of the underlying + * device (this makes it distinct from a generic TextStream object). + * + * @param port_name : the device name. + * @param baud_rate : baud rate. + * @param data_bits : the number of bits in a single message byte. + * @param stop_bits : the number of bits after the data used for error checking. + * @param parity : the parity used for checksums. + * + * @exception StandardException : throws if the connection failed to open. + */ + SerialStream(const std::string& port_name, const BaudRate &baud_rate = BaudRate_115200, const DataBits &data_bits = DataBits_8, + const StopBits &stop_bits = StopBits_1, const Parity &parity = NoParity) + { + ecl_try { + this->device().open(port_name, baud_rate, data_bits, stop_bits, parity); + if ( !this->device().open() ) { + error = this->device().error(); + } + } ecl_catch(StandardException &e) { + ecl_throw(StandardException(LOC,e)); + } + } + virtual ~SerialStream() {}; + +}; + +} // namespace ecl + + +#endif /* ECL_STREAMS_SERIAL_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/shared_file_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/shared_file_stream.hpp new file mode 100644 index 0000000..6a4cd36 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/shared_file_stream.hpp @@ -0,0 +1,78 @@ +/** + * @file /include/ecl/streams/shared_file_stream.hpp + * + * @brief Convenience handles for shared file textstreams. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_SHARED_FILE_STREAMS_HPP_ +#define ECL_STREAMS_SHARED_FILE_STREAMS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "text_stream.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces [SharedFileStream] +*****************************************************************************/ +/** + * @brief Convenience class for SharedFile TextStream definitions. + * + * This class provides a convenient handle for both writing and + * opening TextStream objects. It has no further functionality. + * + * @sa @ref ecl::TextStream "TextStream". + */ +class ecl_streams_PUBLIC SharedFileStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the device manually via device().open() as you would do + * if using a TextStream. + */ + SharedFileStream() {}; + /** + * @brief Convenience constructor for shared file text streams. + * + * This constructor enables RAII style construction of the underlying + * device (this makes it distinct from a generic TextStream object). + * + * @param file_name : output file name. + * @param mode : mode for writing (New, Append). + * + * @exception StandardException : throws if the connection failed to open. + */ + SharedFileStream(const std::string &file_name, const WriteMode &mode = New) { + ecl_try { + if ( !this->device().open(file_name, mode) ) { + error = this->device().error(); + } + } ecl_catch(StandardException &e) { + ecl_throw(StandardException(LOC,e)); + } + } + virtual ~SharedFileStream() {}; +}; + +} // namespace ecl + + +#endif /* ECL_STREAMS_SHARED_FILE_STREAMS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/socket_streams.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/socket_streams.hpp new file mode 100644 index 0000000..012e6b0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/socket_streams.hpp @@ -0,0 +1,127 @@ +/** + * @file /include/ecl/streams/socket_streams.hpp + * + * @brief Convenience handles for socket textstreams. + * + * Convenience handles for socket textstreams. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_SOCKET_STREAMS_HPP_ +#define ECL_STREAMS_SOCKET_STREAMS_HPP_ + +#ifdef ECL_IS_POSIX + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "text_stream.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces [SocketClientStream] +*****************************************************************************/ +/** + * @brief Convenience class for SocketClient TextStream definitions. + * + * This class provides a convenient handle for both writing and + * opening TextStream objects. It has no further functionality. + * + * @sa @ref ecl::TextStream "TextStream". + */ +class ecl_streams_PUBLIC SocketClientStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the device manually via device().open() as you would do + * if using a TextStream. + */ + SocketClientStream() {}; + + /** + * @brief Convenience constructor for output file text streams. + * + * This constructor enables RAII style construction of the underlying + * device (this makes it distinct from a generic TextStream object). + * + * @param host_name : host to connect to. + * @param port_number : port number of the connection. + * + * @exception StandardException : throws if the connection failed to open. + */ + SocketClientStream(const std::string &host_name, const unsigned int &port_number) { + ecl_try { + if ( !this->device().open(host_name, port_number) ) { + error = this->device().error(); + } + } ecl_catch(StandardException &e) { + ecl_throw(StandardException(LOC,e)); + } + } + + virtual ~SocketClientStream() {}; +}; + +/***************************************************************************** +** Interfaces [SocketClientStream] +*****************************************************************************/ +/** + * @brief Convenience class for SocketServer TextStream definitions. + * + * This class provides a convenient handle for both writing and + * opening TextStream objects. It has no further functionality. + * + * @sa @ref ecl::TextStream "TextStream". + */ +class ecl_streams_PUBLIC SocketServerStream : public TextStream { +public: + /** + * @brief Default constructor, underlying device must be manually opened. + * + * This must open the device manually via device().open() as you would do + * if using a TextStream. + */ + SocketServerStream() {}; + + /** + * @brief Convenience constructor for output file text streams. + * + * This constructor enables RAII style construction of the underlying + * device (this makes it distinct from a generic TextStream object). + * + * @param port_number : port number of the connection. + * + * @exception StandardException : throws if the connection failed to open. + */ + SocketServerStream(const unsigned int &port_number) { + try { + this->device().open(port_number); + } catch(StandardException &e) { + throw StandardException(LOC,e); + } + } + + virtual ~SocketServerStream() {}; +}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ + +#endif /* ECL_STREAMS_SOCKET_STREAMS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/string_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/string_stream.hpp new file mode 100644 index 0000000..54fd95f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/string_stream.hpp @@ -0,0 +1,84 @@ +/** + * @file /include/ecl/streams/string_stream.hpp + * + * @brief Convenience handle for virtual string streams. + * + * Convenience handle for virtual string streams. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_STRING_STREAM_HPP_ +#define ECL_STREAMS_STRING_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "text_stream.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ +/** + * @brief Convenience wrapper for string device based textstreams. + * + * This is a wrapper around what could also be used as a + * TextStream object. It provides a more convenient handle and direct + * interfaces to some of the string device functions (otherwise you would + * normally be required to use TextStream's device() method). + */ +class ecl_streams_PUBLIC StringStream : public TextStream { +public: + /** + * @brief Character string representation of the underlying device's contents. + * + * This returns a null terminates string representing the contents of the + * underlying device's internal buffer. Note that this returns the + * full buffer, not just the unread parts. + * + * @return const char* : pointer to the device's internal buffer. + */ + const char* c_str() { return this->io_device.c_str(); } + + /** + * @brief String representation of the underlying device's contents. + * + * This generates a c++ style string representing the contents of the + * underlying device's internal buffer. Note that this returns the + * full buffer, not just the unread parts. + * + * @return string : string representation of the underlying device's internal buffer. + */ + std::string str() { return this->io_device.str(); } + + /** + * @brief Clears the underlying device's internal buffers. + * + * Clears the underlying device's internal character buffer and resets + * read/write location pointers. + */ + void clear() { io_device.clear(); } + + virtual ~StringStream() {} +}; + +} // namespace ecl + + + + +#endif /* ECL_STREAMS_STRING_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_stream.hpp new file mode 100644 index 0000000..e4ee861 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_stream.hpp @@ -0,0 +1,103 @@ +/** + * @file /include/ecl/streams/text_stream.hpp + * + * @brief Convenience header for various text streams. + * + * Convenience header for various text streams. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_TEXT_STREAM_HPP_ +#define ECL_STREAMS_TEXT_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "text_streams/base_text_stream.hpp" +#include "text_streams/output_text_stream.hpp" +#include "text_streams/input_text_stream.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [TextStream] +*****************************************************************************/ + +/** + * @brief A text streaming interface. + * + * This connects to an underlying device and enables text streaming to and + * from the device. The device type (determined by input and output + * device concept checks) determines the type of interface that is + * brought into the textstream instance, either input, output or both. + * + * Usage: + * + * Instantiating + * + * To open the underlying device, + * + * @code + * TextStream ofstream; + * ofstream.device().open("dudes.txt",New); + * @endcode + * + * Streaming + * + * Usage follows very similar to the standard c++ streams. + * + * @code + * ofstream << "dudes " << 32.36; + * ofstream.flush(); + * @endcode + * + * Formatting + * + * These streams are usable with the format classes in ecl_formatters. + * + * @code + * Format format; format.width(5); format.precision(2); + * double d = 1.0/3.0; + * ostream << format(d); // This will send 0.33 to the stream. + * ostream.flush(); + * @endcode + * + * Error Checking + * + * Output streams can generate errors that are not so easily checked compared with handling devices directly. + * To check for failure, ecl streams use a mechanism similar to that of the standard cout stream. + * + * @code + * ostream << 32.1; + * if ( ostream.fail() ) { + * std::cout << ostream.errorMessage() << std::endl; + * } + * @endcode + * + * You can also use the errorStatus() method to retrieve the exact error flag (enumeration). + * + * @sa interfaces::InputTextStream, interfaces::OutputTextStream, interfaces::BaseTextStream. + */ +template +class ECL_PUBLIC TextStream : public interfaces::InputTextStream::value >, + public interfaces::OutputTextStream::value > { +public: + virtual ~TextStream() {}; + +}; + +} // namespace ecl + +#endif /* ECL_STREAMS_TEXT_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/CMakeLists.txt new file mode 100644 index 0000000..363545a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/streams/text_streams) + diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/base_text_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/base_text_stream.hpp new file mode 100644 index 0000000..a74868b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/base_text_stream.hpp @@ -0,0 +1,101 @@ +/** + * @file /include/ecl/streams/text_streams/base_text_stream.hpp + * + * @brief Base interface for text streams. + * + * @date November 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_BASE_TEXT_STREAM_HPP_ +#define ECL_STREAMS_BASE_TEXT_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace interfaces { + +/***************************************************************************** +** Interface [BaseTextStream] +*****************************************************************************/ +/** + * @brief Parent class for text stream functionality. + * + * This brings the common io functionality together for both input and + * output text streams, namely the device and + * its handlers. + * + * @tparam Device : the underlying device type. + */ +template +class ECL_PUBLIC BaseTextStream { +public: + BaseTextStream() : error(ecl::NoError) {}; + virtual ~BaseTextStream() {} + Device& device(); + bool fail() const; + const ecl::Error& errorStatus() const; + +protected: + ecl::Error error; + Device io_device; +}; + +/***************************************************************************** +** Implementation [BaseTextStream] +*****************************************************************************/ +/** + * @brief Provides access to the underlying output device. + * + * Provides access to the underlying output device. + * @return Device : reference to the underlying output device. + */ +template +Device& BaseTextStream::device() { return io_device; } + +/** + * @brief Denotes the status of the last device operation. + * + * This returns true if the last (read/write) operation failed. This can be due to the + * input being incorrect (e.g. letters in a value when reading a digit), or + * because it tried to read past the end of the stream, or the stream is in a + * bad state. + * return bool : true if the last stream operation failed, false otherwise. + **/ +template +bool BaseTextStream::fail() const { + if ( error.flag() != ecl::NoError ) { + return true; + } else { + return false; + } +} +/** + * @brief Enumeration indicating the exit status of the last read operation. + * + * This returns an enumeration that indicates the exit status of the last + * read operation. + * + * @return ErrorFlag : the error status indicator (NoError is a valid state). + */ +template +const ecl::Error& BaseTextStream::errorStatus() const { + return error; +} + +} // namespace interfaces +} // namespace ecl + +#endif /* ECL_STREAMS_BASE_TEXT_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/input_text_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/input_text_stream.hpp new file mode 100644 index 0000000..932c9e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/input_text_stream.hpp @@ -0,0 +1,722 @@ +/** + * @file /include/ecl/streams/text_streams/input_text_stream.hpp + * + * @brief Input text streaming interface and implementation. + * + * Provides an input text streaming interface that can be connected + * to input devices. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_INPUT_TEXT_STREAM_HPP_ +#define ECL_STREAMS_INPUT_TEXT_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "base_text_stream.hpp" +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace interfaces { + +/***************************************************************************** +** Interface [InputTextStream] +*****************************************************************************/ + +/** + * @brief Parent template for input text streams. + * + * This template is defined so that is can provide an empty + * interface if the calling device is not in fact an input device. + * The actual input interface is defined in the boolean true specialisation. + * + * @tparam Device : underlying device connected to the stream. + * @tparam InputDevice : boolean indicating if the device is an input device or not. + * + * @sa InputTextStream + */ +template +class ECL_PUBLIC InputTextStream { +}; + +/** + * @brief Input text stream interface. + * + * Defines the appropriate functionality required for input text streams. + * + * @tparam Device : this must be a class that satisfies the + * input device concept (refer to the documentation in ecl_concepts for details). + * + * Usage: + * + * - Instantiate + * - Open the underlying device + * - Stream + * + * @code + * TextStream ifstream; + * ifstream.device().open("dudes.txt"); + * char c; + * ifstream >> c; + * @endcode + * + * Some notes - text streams support reading by one of three methods: + * - readln() + * - element by element (separated by whitespace or carriage returns + * - raw characters (by default this is disabled, enable with enableRawCharReads()) + **/ +template +class ECL_PUBLIC InputTextStream : public virtual BaseTextStream { +public: + /********************* + ** Constructors + **********************/ + InputTextStream(); + virtual ~InputTextStream() {} + + /********************* + ** Streaming Operators + **********************/ + InputTextStream& operator >> ( char &c ); + InputTextStream& operator >> ( std::string &s ); + InputTextStream& operator >> ( short &i ); + InputTextStream& operator >> ( int &i ); + InputTextStream& operator >> ( long &i ); + InputTextStream& operator >> ( unsigned char &c ); + InputTextStream& operator >> ( unsigned short &i ); + InputTextStream& operator >> ( unsigned int &i ); + InputTextStream& operator >> ( unsigned long &i ); + InputTextStream& operator >> ( float &f ); + InputTextStream& operator >> ( double &d ); + InputTextStream& operator >> ( long long &i ); + InputTextStream& operator >> ( unsigned long long &i ); + InputTextStream& operator >> ( bool &b ); + + /********************* + ** Non-Streaming API + **********************/ + void enableRawCharReads(); + void disableRawCharReads(); + +private: + bool raw_char_reads; + + /********************* + ** Private Parsers + **********************/ + bool skipLeadingWhiteSpace(char &c); + template + bool getIntegerFromStream(Number &i); + template + bool parseHexInteger(Number &i); + template + bool getFloatFromStream(Number &f); +}; + +/***************************************************************************** +** Implementation [InputTextStream] +*****************************************************************************/ +/** + * @brief Connects the stream to an input device. + * + * Connects the text stream to the associated input device. Use + * the device() handle to properly open the device, e.g. + * + * @code + * InputTextStream ifstream; + * @endcode + **/ +template +InputTextStream::InputTextStream() : raw_char_reads(false) { + ecl_compile_time_concept_check(ecl::InputCharDeviceConcept); +} + +/***************************************************************************** +** Implementation [InputTextStream][Streaming Operators] +*****************************************************************************/ +/** + * @brief Reads an unformatted char to the stream. + * + * Reads an unformatted char from the stream. Note, this will absolutely + * read every character in the device. + * + * @param c : input value being read from the stream. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream & InputTextStream::operator >> ( char &c ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + + if ( !raw_char_reads ) { + if( skipLeadingWhiteSpace(c) ) { + this->error = NoError; + } else { + this->error = ReadError; + } + } else { + if ( this->io_device.read(c) == 1 ) { + this->error = NoError; + } else { + this->error = ReadError; + } + } + return *this; +} + +/** + * @brief Reads an unformatted string from the stream. + * + * Reads an unformatted string from the stream. Essentially, this reads characters into a string until + * either a space or a newline char is reached, that is, it reads whole words at a time and removes any + * leading or trailing space/newline entities. + * + * @param s : input being read from the stream. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( std::string &s ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + + char c; + if ( skipLeadingWhiteSpace(c) ) { + s.clear(); + do { + s.push_back(c); + if( this->io_device.read(c) < 1 ) { + this->error = ReadError; + break; + } + } while ( ( c != ' ' ) && ( c != '\n' ) ); + this->error = NoError; + } else { + this->error = ReadError; + } + + // Original method - reads a whole line (must be terminated by a \n) +// static char buffer[80]; +// this->io_device.read(&buffer[0],80); +// s.assign(buffer); + return *this; +} + +/** + * @brief Converts a value from the stream to a short. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( short &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + + return *this; +} + +/** + * @brief Converts a value from the stream to an int. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( int &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to a long. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( long &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} +/** + * @brief Converts a value from the stream to a long long. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( long long &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} +/** + * @brief Converts a value from the stream to an unsigned char. + * + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * + * @param uc : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( unsigned char &uc ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(uc) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to an unsigned short. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( unsigned short &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to an unsigned int. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( unsigned int &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to an unsigned long. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( unsigned long &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to an unsigned long long. + * If there is an error at any part of the conversion (non-digit, too large) it will leave the input + * argument unchanged and set the fail() response to true. + * @param i : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( unsigned long long &i ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getIntegerFromStream(i) ) { + this->error = NoError; + } // Real errors are handled internally in getIntegerFromStreams + return *this; +} + + +/** + * @brief Converts a value from the stream to a float. + * If there is an error at any part of the conversion it will leave the input + * argument unchanged and set the fail() response to true. + * @param f : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( float &f ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getFloatFromStream(f) ) { + this->error = NoError; + } // Real errors are handled internally in getFloatFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to a float. + * If there is an error at any part of the conversion it will leave the input + * argument unchanged and set the fail() response to true. + * @param d : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( double &d ) { + + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( getFloatFromStream(d) ) { + this->error = NoError; + } // Real errors are handled internally in getFloatFromStreams + return *this; +} + +/** + * @brief Converts a value from the stream to a bool. + * If there is an error at any part of the conversion it will leave the input + * argument unchanged and set the fail() response to true. Valid text input for a bool value + * includes 'true', 'TRUE', 'false', 'FALSE'. + * + * @param b : input value to be filled. + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return InputTextStream : returns the stream for further manipulation. + **/ +template +InputTextStream& InputTextStream::operator >> ( bool &b ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + std::string s; + *this >> s; + + if ( this->fail() ) { // string could not be read + return *this; // error already set + } + + if ( ( s == "true" ) || ( s == "TRUE" ) || ( s == "True" ) ) { + b = true; + this->error = NoError; + } else if ( ( s == "false" ) || ( s == "FALSE" ) || ( s == "False" ) ) { + b = false; + this->error = NoError; + } else { + this->error = ConversionError; + } + return *this; +} + +/***************************************************************************** +** Implementation [InputTextStream][Non-Streaming Interface] +*****************************************************************************/ + +/** + * @brief This permits true char by char reads (including space and newline chars). + * + * By default, text streams read chars (via the operator>> (char &c)) method in the same + * way as every other operator is used, that is, element by element. As a result, any + * leading whitespace or newline characters are ignored. By calling this function, you + * can disable this functionality (for the operator>> (char&c) method only) so true + * byte by byte reads can be performed. This is usually only useful for things like + * serial devices - not so much for files or standard input style devices. + * + * @sa disableRawCharReads(). + */ +template +void InputTextStream::enableRawCharReads() { raw_char_reads = true; } + +/** + * @brief This ensures char reads are read element by element (not byte by byte). + * + * This has the opposite functionality to enableRawCharReads(). See that method for + * more information. + * + * @sa enableRawCharReads(). + */ +template +void InputTextStream::disableRawCharReads() { raw_char_reads = false; } + + +/***************************************************************************** +** Implementation [InputTextStream][Private Parsers] +*****************************************************************************/ + +/** + * @brief Private implementation that churns through any leading white space. + * + * This checks for leading space and newline characters. If successful, + * it returns the first read character in its argument. + * + * @param c : if successful, the first legitimate character is returned here. + * @return bool : true if successful, false otherwise. + */ +template +bool InputTextStream::skipLeadingWhiteSpace(char &c) +{ + do { + if( this->io_device.read(c) < 1 ) { // Fail if either there is a read error OR there is nothing in the device. + this->error = ReadError; + return false; + } + } while ( ( c == ' ' ) || ( c == '\n' ) ); + return true; +} + +/** + * Parses a hex number from a stream into an integral type. + * @param i : the integer to stream the value to. + */ +template +template +bool InputTextStream::parseHexInteger(Number &i) +{ + char c; + static int digits[25]; + static const short ceiling = numeric_limits::maximum/10; + + i = 0; + int j = 0; + while ( j < 25 ) { + long n = this->io_device.read(c); + if ( n < 0 ) { + this->error = ReadError; + return false; + } else if ( n == 0 ) { + break; // nothing more to read. + } + if ( ( c >= '0' ) && ( c <= '9') ) { + digits[j] = c - '0'; + } else if ( ( c >= 'a' ) && ( c <= 'f') ) { + digits[j] = 10 + c - 'a'; + } else if ( ( c >= 'A' ) && ( c <= 'F') ) { + digits[j] = 10 + c - 'A'; + } else { + break; // No more valid characters to read. + } + ++j; + } + if ( j == 0 ) { + this->error = ReadError; + return false; + } + + short number = 0; + for ( int k = 0; k < j; ++k ) { + if ( number < ceiling ) { + number = 16*number + (digits[k]); + } else { + this->error = OutOfRangeError; + return false; + } + } + i = number; + return true; +} + +/** + * Parses a value from a stream into an integral type. + * + * @param i : the integral type variable to stream the value into. + */ +template +template +bool InputTextStream::getIntegerFromStream(Number &i) { + + static char digits[25]; // 20 is the maximum needed on a 64 bit system for a long type + static const Number ceiling = ecl::numeric_limits::maximum/10; + char c = ' '; + Number sign_multiplier = 1; + Number number; + + if ( !skipLeadingWhiteSpace(c) ) { return false; } + + if ( c == '-' ) { // Negative + if ( std::numeric_limits::min() != 0 ) { + sign_multiplier = -1; + if ( this->io_device.read(c) < 1 ) { + this->error = ReadError; + return false; + } + } // else do nothing and continue, an error will be found at the next step. + } else if ( c == '+' ) { // Positive + if ( this->io_device.read(c) < 1 ) { + this->error = ReadError; + return false; + } + } else if ( c == '0' ) { + long n = this->io_device.read(c); + if ( ( n == 0 ) || ( c == ' ' ) || ( c == '\n' ) ) { // It's just a single zero. + i = 0; + return true; + } else if ( n < 0 ) { + this->error = ReadError; + return false; + } else if ( c == 'x' ) { + return parseHexInteger(i); + } else { + // its a regular integer, just continue + } + } else if ( c == 'x' ) { + return parseHexInteger(i); + } + + /********************* + ** Parse reg. integer + **********************/ + int j = 0; + while ( ( c >= '0' ) && ( c <= '9') && ( j < 25 ) ) { + digits[j] = c; + j++; + long n = this->io_device.read(c); + if ( n < 0 ) { + this->error = ReadError; + return false; + } else if ( n == 0 ) { + break; + } else { // n > 1 + } + } + if ( j == 0 ) { + this->error = ConversionError; + return false; + } + number = 0; + for ( int k = 0; k < j; ++k ) + { + if ( number < ceiling ) + { + number = 10*number + (digits[k] - '0'); + } else { + this->error = OutOfRangeError; + return false; + } + } + i = sign_multiplier*number; + + return true; +} + +template +template +bool InputTextStream::getFloatFromStream(Number &f) { + static const int bufferSize = 25; + static char digits[bufferSize]; // 20 is the maximum needed on a 64 bit system for a long type + char c = ' '; + int integral_length = 0; + int decimal_length = 0; + Number sign_multiplier = 1; + Number number; + + if ( !skipLeadingWhiteSpace(c) ) { return false; } + + if ( c == '-' ) { + sign_multiplier = -1; + if ( this->io_device.read(c) < 1 ) { this->error = ReadError; return false; } + } else if ( c == '+' ) { + if ( this->io_device.read(c) < 1 ) { this->error = ReadError; return false; } + } + number = 0; + /****************************************** + ** Integral part + *******************************************/ + while ( ( c >= '0' ) && ( c <= '9') && ( integral_length < bufferSize ) ) { + digits[integral_length] = c; + long n = this->io_device.read(c); + if ( n < 0 ) { + this->error = ReadError; return false; + } else if ( n == 0 ) { + break; + } else { // n > 1 + integral_length++; + } + } + for ( int k = 0; k < integral_length; ++k ) { + number = 10*number + (digits[k] - '0'); + } + + if ( c == '.' ) { + float frac_multiplier = 1; + if ( this->io_device.read(c) < 1 ) { this->error = ReadError; return false; } + /****************************************** + ** Decimal part + *******************************************/ + while ( ( c >= '0' ) && ( c <= '9') && ( decimal_length < bufferSize ) ) { + digits[decimal_length] = c; + long n = this->io_device.read(c); + if ( n < 0 ) { + this->error = ReadError; return false; + } else if ( n == 0 ) { + break; + } else { // n > 1 + decimal_length++; + } + } + for ( int k = 0; k < decimal_length; ++k ) { + frac_multiplier *= 0.1f; + number = number + frac_multiplier*(digits[k] - '0'); + } + } + + if ( (integral_length+decimal_length) == 0 ) { + this->error = ConversionError; + return false; + } + + f = sign_multiplier*number; + + return true; +} + +} // namespace interfaces +} // namespace ecl + +#endif /* ECL_STREAMS_INPUT_TEXT_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/output_text_stream.hpp b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/output_text_stream.hpp new file mode 100644 index 0000000..2b64faf --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/include/ecl/streams/text_streams/output_text_stream.hpp @@ -0,0 +1,369 @@ +/** + * @file /include/ecl/streams/text_streams/output_text_stream.hpp + * + * @brief Output text streaming interface and implementation. + * + * Provides an output text streaming interface that can be connected + * to output devices. + * + * @date October 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STREAMS_OUTPUT_TEXT_STREAM_HPP_ +#define ECL_STREAMS_OUTPUT_TEXT_STREAM_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "../manipulators/manipulator.hpp" +#include "../macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace interfaces { + +/***************************************************************************** +** Interface [OutputTextStream] +*****************************************************************************/ + +/** + * @brief Parent template for output text streams. + * + * This template is defined so that is can provide an empty + * interface if the calling device is not in fact an output device. + * The actual output interface is defined in the boolean true specialisation. + * + * @tparam Device : underlying device connected to the stream. + * @tparam OutputDevice : boolean indicating if the device is an output device or not. + * + * @sa OutputTextStream + */ +template +class ECL_PUBLIC OutputTextStream {}; + +/** + * @brief Output text stream interface. + * + * Defines the appropriate functionality required for output text streams. + * + * @tparam Device : this must be a class that satisfies the + * output device concept (refer to the documentation in ecl_concepts for + * details). + * + * Usage: + * + * - Instantiate + * - Open the underlying device + * - Stream + * + * @code + * TextStream ofstream; + * ofstream.device().open("dudes.txt",New); + * ofstream << "dudes " << 32.36; + * ofstream.flush(); + * @endcode + **/ +template +class ECL_PUBLIC OutputTextStream : public virtual BaseTextStream { + public: + /** + * @brief Connects the stream to an output device. + * + * Connects the text stream to the associated output device. Use + * the device() handle to properly open the device, e.g. + * + * @code + * OutputTextStream ofstream; + * ofstream.device().open("dudes.txt",New); + * @endcode + **/ + OutputTextStream() : + toCharString(30) // character buffer size + { + ecl_compile_time_concept_check(OutputCharDeviceConcept); + }; + + virtual ~OutputTextStream() {} + + OutputTextStream& operator << ( const char &c ); + OutputTextStream& operator << ( const char *s ); + OutputTextStream& operator << ( const std::string &s ); + OutputTextStream& operator << ( const short &i ); + OutputTextStream& operator << ( const int &i ); + OutputTextStream& operator << ( const long &i ); + OutputTextStream& operator << ( const long long &i ); + OutputTextStream& operator << ( const unsigned short &i ); + OutputTextStream& operator << ( const unsigned int &i ); + OutputTextStream& operator << ( const unsigned long &i ); + OutputTextStream& operator << ( const unsigned long long &i ); + OutputTextStream& operator << ( const bool b ); + OutputTextStream& operator << ( const float &f ); + OutputTextStream& operator << ( const double &d ); + + /********************* + * Friend Manipulators + *********************/ + template + OutputTextStream& operator << ( ecl::Manipulator &manipulator ) + { + manipulator.insert(*this); + return *this; + } + + /** + * Provides a streaming operator for handling output textstream manipulators. Manipulators are simple + * functions that accept the stream as input and manipulate it in a minor way. They can hold no state. + * The most common example of such a manipulator is the endln manipulator. This manipulator works in + * the same fashion as the c++ endl manipulator. + **/ +// friend interfaces::OutputTextStream& operator << (interfaces::OutputTextStream& ostream, void (*manipulator)(interfaces::OutputTextStream&) ) +// { +// (*manipulator)(ostream); +// return ostream; +// } + + /********************* + ** Buffer functionality + **********************/ + void flush(); + + private: + ecl::Converter toCharString; +}; + +/***************************************************************************** +** Implementation [OutputTextStream] +*****************************************************************************/ + +/** + * @brief Sends an unformatted char to the stream. + * Sends an unformatted char to the stream. + * @param c : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator<< ( const char& c ) { + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + this->io_device.write(c); + return *this; +} +/** + * @brief Sends an unformatted char string to the stream. + * Sends an unformatted char string to the stream. + * + * @param s : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const char *s ) { + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + this->io_device.write(s,strlen(s)); + return *this; +} + +/** + * @brief Sends an unformatted string to the stream. + * Sends an unformatted string to the stream. + * + * @param s : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const std::string &s ) { + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + this->io_device.write(&s[0],s.size()); + return *this; +} +/** + * @brief Sends an unformatted short to the stream. + * Sends an unformatted short to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const short &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} +/** + * @brief Sends an unformatted int to the stream. + * Sends an unformatted int to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const int &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} + +/** + * @brief Sends an unformatted long to the stream. + * Sends an unformatted long to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const long &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} + +/** + * @brief Sends an unformatted long long to the stream. + * Sends an unformatted long long to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const long long &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} + +/** + * @brief Sends an unformatted unsigned short to the stream. + * Sends an unformatted unsigned short to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const unsigned short &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} + +/** + * @brief Sends an unformatted unsigned int to the stream. + * Sends an unformatted unsigned int to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const unsigned int &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} + +/** + * @brief Sends an unformatted unsigned long to the stream. + * Sends an unformatted unsigned long to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const unsigned long &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} +/** + * @brief Sends an unformatted unsigned long long to the stream. + * Sends an unformatted unsigned long long to the stream. + * @param i : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const unsigned long long &i ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(i); + return *this; +} +/** + * @brief Sends a boolean to the stream. + * Sends a boolean to the stream. + * @param b : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const bool b ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + if ( b ) { *this << "true"; } else { *this << "false"; }; + return *this; +} + +/** + * Sends an unformatted float to the stream. + * @param f : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation + **/ +template +OutputTextStream& OutputTextStream::operator << ( const float &f ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(f); + return *this; +} + +/** + * Sends an unformatted double to the stream. + * @param d : input value being sent to the stream + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + * @return OutputTextStream : returns the stream for further manipulation. + **/ +template +OutputTextStream& OutputTextStream::operator << ( const double &d ) +{ + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + *this << toCharString(d); + return *this; +} + +/** + * @brief Flushes the underlying device's buffer. + * + * Flushes the underlying device's buffer. + * + * @exception ecl::StandardException : throws if the underlying device has not been opened [debug mode only]. + **/ +template +void OutputTextStream::flush() { + ecl_assert_throw(this->io_device.open(),ecl::StandardException(LOC,OpenError,"The underlying stream device is not open.")); + this->io_device.flush(); +} + +} // namespace interfaces +} // namespace ecl + +#endif /* ECL_STREAMS_OUTPUT_TEXT_STREAM_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_streams/package.xml b/ros2_ws/src/ecl_core/ecl_streams/package.xml new file mode 100644 index 0000000..18710b3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/package.xml @@ -0,0 +1,44 @@ + + + ecl_streams + 1.2.1 + + These are lightweight text streaming classes that connect to standardised + ecl type devices. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_streams + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_errors + ecl_concepts + ecl_devices + ecl_time + ecl_converters + ecl_type_traits + + ecl_license + ecl_errors + ecl_concepts + ecl_devices + ecl_time + ecl_converters + ecl_type_traits + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/src/CMakeLists.txt new file mode 100644 index 0000000..858d40d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + +add_subdirectory(examples) \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/src/examples/CMakeLists.txt new file mode 100644 index 0000000..da918e4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/examples/CMakeLists.txt @@ -0,0 +1,22 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_streams_add_example name) + set(target_name ecl_time_example_${name}) + add_executable(${target_name} ${name}.cpp) + target_link_libraries(${target_name} + ${PROJECT_NAME} + ecl_devices::ecl_devices + ecl_threads::ecl_threads + ) + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ${target_name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_streams_add_example(console_streams) +ecl_streams_add_example(log_streams) diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/examples/console_streams.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/examples/console_streams.cpp new file mode 100644 index 0000000..7d08560 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/examples/console_streams.cpp @@ -0,0 +1,152 @@ +/** + * @file /src/examples/console_streams.cpp + * + * @brief Demo for the console streams. + * + * @date October 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/streams/text_stream.hpp" +#include "../../include/ecl/streams/console_streams.hpp" +#include "../../include/ecl/streams/manipulators/end_of_line.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::OConsole; +using ecl::IConsole; +using ecl::endl; +using ecl::TextStream; +using ecl::IConsoleStream; +using ecl::OConsoleStream; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + bool test_istreams = false; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " OConsole Stream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "These can't really be tested very easily by google tests, so" << std::endl; + std::cout << "it's just provided here as a demo, but functionally is a" << std::endl; + std::cout << "unit test (requiring human approval)." << std::endl; + std::cout << std::endl; + + OConsoleStream ostream; + + std::cout << "Streaming char." << std::endl; + ostream << 'c' << '\n'; + std::cout << "Streaming char string." << std::endl; + ostream << "Dude\n"; + std::cout << "Streaming string." << std::endl; + string dude("dude_string\n"); + ostream << dude; + std::cout << "Streaming integers." << std::endl; + short si = 1; + ostream << si << '\n'; + int i = 2; + ostream << i << '\n'; + long l = 3; + ostream << l << '\n'; + long long ll = 4; + ostream << ll << '\n'; + unsigned short us = 5; + ostream << us << '\n'; + unsigned int ui = 6; + ostream << ui << '\n'; + unsigned long ul = 77; + ostream << ul << '\n'; + unsigned long long ull = 8888; + ostream << ull << '\n'; + std::cout << "Streaming temporary integers." << std::endl; + ostream << 77 << '\n'; + std::cout << "Streaming a boolean." << std::endl; + bool test = true; + ostream << test << '\n'; + ostream << false << '\n'; + std::cout << "Streaming floating point values." << std::endl; + float f = 32.1; + double d = -33.3; + ostream << f << '\n'; + ostream << d << '\n'; + + std::cout << "Flushing" << std::endl; + ostream.flush(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " OConsole Manipulators" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ostream << "dude with an ecl::endl" << endl; + + if ( test_istreams ) { + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " IConsole Stream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + char c; + string response; + IConsoleStream istream; + // TextStream istream; + + std::cout << "Enter a char." << std::endl; + istream >> c; + std::cout << "Char read: " << c << std::endl; + std::cout << "Enter a word." << std::endl; + istream >> response; + std::cout << "Word read: " << response << std::endl; + std::cout << "Enter a short: " << std::endl; + istream >> si; + if ( istream.fail() ) { + std::cout << "Short read failed: " << istream.errorStatus().what() << std::endl; + } else { + std::cout << "Short read: " << si << std::endl; + } + std::cout << "Enter a bool: " << std::endl; + istream >> test; + if ( istream.fail() ) { + std::cout << "Bool read failed: " << istream.errorStatus().what() << std::endl; + } else { + std::cout << "Bool read: "; + if ( test ) { + std::cout << "true" << std::endl; + } else { + std::cout << "false" << std::endl; + } + } + std::cout << "Enter a double:" << std::endl; + istream >> d; + if ( istream.fail() ) { + std::cout << "Double read failed: " << istream.errorStatus().what() << std::endl; + } else { + std::cout << "Double read: " << d << std::endl; + } + } + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/examples/log_streams.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/examples/log_streams.cpp new file mode 100644 index 0000000..2fdb7e7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/examples/log_streams.cpp @@ -0,0 +1,96 @@ +/** + * @file /src/examples/log_streams.cpp + * + * @brief Demo for log streams. + * + * @date December 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/streams/log_stream.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::New; +using ecl::LogStream; +using ecl::Thread; + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace demos { + +/***************************************************************************** +** Enums +*****************************************************************************/ + +enum LogModes { + Warning, + Error, + Debug, +}; + +void enableModes( LogStream &log_stream ) { + log_stream.enableHeader(); + log_stream.enableTimeStamp(); + log_stream.enableMode(Warning,"WARNING"); + log_stream.enableMode(Error,"ERROR"); + log_stream.enableMode(Debug,"DEBUG"); +} + +void f() { + LogStream logstream("test.log",New); + enableModes(logstream); + LOG(logstream,Debug) << "Debug message from a threaded function.\n"; + FLUSH(logstream); +} + +} // namespace demos +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::demos; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " LogStream" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "This program will log from main and a parallel thread" << std::endl; + std::cout << "to a shared log file call 'test.log'." << std::endl; + + LogStream logstream("test.log",New); + enableModes(logstream); + Thread thread(f); + LOG(logstream,Debug) << "Debug message from main.\n"; + FLUSH(logstream); + thread.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/src/lib/CMakeLists.txt new file mode 100644 index 0000000..a73f59d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/lib/CMakeLists.txt @@ -0,0 +1,41 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(ecl_streams ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_concepts::ecl_concepts + ecl_converters::ecl_converters + ecl_devices::ecl_devices + ecl_errors::ecl_errors + ecl_time::ecl_time + ecl_type_traits::ecl_type_traits +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/lib/log_stream.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/lib/log_stream.cpp new file mode 100644 index 0000000..4fd972a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/lib/log_stream.cpp @@ -0,0 +1,71 @@ +/** + * @file /src/lib/log_stream.cpp + * + * @brief Customised logging implementation. + * + * @date December 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/streams/log_stream.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; + +/***************************************************************************** +** Implementation [LogStream] +*****************************************************************************/ + +void LogStream::enableHeader() { write_header = true; } +void LogStream::disableHeader() { write_header = false; } +void LogStream::enableTimeStamp() { write_stamp = true; } +void LogStream::disableTimeStamp() { write_stamp = false; } + +void LogStream::enableMode(int mode, std::string header) { modes.insert( std::make_pair(mode,header) ); } +void LogStream::disableMode(int mode) { modes.erase(mode); } + +bool LogStream::isEnabled() { + if ( modes.size() > 0 ) { + return true; + } else { + return false; + } +} + +bool LogStream::isModeEnabled(int mode) { + + if( modes.count(mode) > 0 ) { + return true; + } else { + return false; + } +} + +LogStream& LogStream::log(int mode) { + if ( write_stamp ) { + (*this) << timestamp.stamp() << " "; + } + if ( write_header ) { + (*this) << "[" << modes[mode] << "] "; + } + if ( write_stamp || write_header ) { + (*this) << ": "; + } + return (*this); +} + +} // namespace ecl + diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/lib/manipulators.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/lib/manipulators.cpp new file mode 100644 index 0000000..253635f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/lib/manipulators.cpp @@ -0,0 +1,29 @@ +/** + * @file /src/lib/manipulators.cpp + * + * @brief Manipulators for text streams. + * + * @date November 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/streams/manipulators/end_of_line.hpp" +#include "../../include/ecl/streams/manipulators/clear_screen.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +EndOfLine endl; +ClearScreen clrscr; + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_streams/src/test/CMakeLists.txt new file mode 100644 index 0000000..f74209e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/test/CMakeLists.txt @@ -0,0 +1,19 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_streams_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Tests +############################################################################### + +ecl_streams_add_gtest(file_streams) +ecl_streams_add_gtest(string_streams) + diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/test/file_streams.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/test/file_streams.cpp new file mode 100644 index 0000000..f52322c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/test/file_streams.cpp @@ -0,0 +1,140 @@ +/** + * @file /src/test/file_streams.cpp + * + * @brief Unit Test for the file streams. + * + * @date September, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/streams/file_streams.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::OFile; +using ecl::Append; +using ecl::New; +using ecl::StandardException; +using ecl::TextStream; +using ecl::OFileStream; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(OFileStreamTests,construct) { + OFileStream ostream("dude_stream.txt",New); + EXPECT_TRUE(ostream.device().open()); +} + +TEST(OFileStreamTests,writeChar) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + ostream << 'c' << '\n'; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(OFileStreamTests,writeCharString) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + ostream << "Dude\n"; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(OFileStreamTests,writeString) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + string dude("dude_string\n"); + ostream << dude; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(OFileStreamTests,writeIntegralTypes) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + short si = 1; + ostream << si << '\n'; + int i = 2; + ostream << i << '\n'; + long l = 3; + ostream << l << '\n'; + long long ll = 4; + ostream << ll << '\n'; + unsigned short us = 5; + ostream << us << '\n'; + unsigned int ui = 6; + ostream << ui << '\n'; + unsigned long ul = 77; + ostream << ul << '\n'; + unsigned long long ull = 8888; + ostream << ull << '\n'; + ostream << 77 << '\n'; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(OFileStreamTests,writeBool) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + bool test = true; + ostream << test << '\n'; + ostream << false << '\n'; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +TEST(OFileStreamTests,writeFloatTypes) { + OFileStream ostream("dude_stream.txt",Append); + bool result = true; + try { + float f = 32.1; + double d = -33.3; + ostream << f << '\n'; + ostream << d << '\n'; + ostream.flush(); + } catch ( const StandardException &e ) { + result = false; + } + EXPECT_TRUE(result); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_streams/src/test/string_streams.cpp b/ros2_ws/src/ecl_core/ecl_streams/src/test/string_streams.cpp new file mode 100644 index 0000000..ef88352 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_streams/src/test/string_streams.cpp @@ -0,0 +1,104 @@ +/** + * @file /src/test/string_streams.cpp + * + * @brief Unit Test for the string stream. + * + * @date December 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/streams/string_stream.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::string; +using ecl::StringStream; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(StringStreams,floatTypes) { + StringStream sstream; + float f = 33.33; + double d = -1.0; + sstream << f; + sstream >> d; + EXPECT_FALSE(sstream.fail()); + // Give it some room for rounding off + EXPECT_GT(33.34,d); + EXPECT_LT(33.32,d); +} + +TEST(StringStreams,clearStream) { + StringStream sstream; + sstream << "dude"; + sstream.clear(); + sstream << "aha"; + EXPECT_FALSE(sstream.fail()); + EXPECT_EQ(string("aha"),sstream.str()); +} + +TEST(StringStreams,integralTypes) { + StringStream sstream; + int i = 3; + int j = -1; + sstream << i; + sstream >> j; + EXPECT_FALSE(sstream.fail()); + // Give it some room for rounding off + EXPECT_EQ(3,j); +} + +TEST(StringStreams,hexTypes) { + StringStream sstream; + int j = -1; + sstream << "0xA0"; + sstream >> j; + EXPECT_FALSE(sstream.fail()); + // Give it some room for rounding off + EXPECT_EQ(160,j); +} +TEST(StringStreams,multipleOps) { + StringStream sstream; + string s; + sstream << "Hello"; + sstream >> s; + EXPECT_FALSE(sstream.fail()); + EXPECT_EQ(string("Hello"),s); + sstream << "Dude"; + sstream >> s; + EXPECT_FALSE(sstream.fail()); + EXPECT_EQ(string("Dude"),s); +} + +TEST(StringStreams,readEmptyFail) { + StringStream sstream; + int j; + sstream >> j; + EXPECT_TRUE(sstream.fail()); +} + +TEST(StringStreams,remaining) { + StringStream sstream; + sstream << "Dude"; + EXPECT_EQ(4U,sstream.device().remaining()); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_threads/.cproject b/ros2_ws/src/ecl_core/ecl_threads/.cproject new file mode 100644 index 0000000..16abba7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/.cproject @@ -0,0 +1,714 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + all + + true + + true + + true + + + + + + make + + + + clean + + true + + true + + true + + + + + + make + + + + test + + true + + true + + true + + + + + + make + + + + tests + + true + + true + + true + + + + + + make + + + + install + + true + + true + + true + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_threads/.project b/ros2_ws/src/ecl_core/ecl_threads/.project new file mode 100644 index 0000000..12c83ea --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/.project @@ -0,0 +1,82 @@ + + + ecl_threads + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?children? + ?name?=outputEntries\|?children?=?name?=entry\\\\\\\|\\\|\|| + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_threads/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_threads/CHANGELOG.rst new file mode 100644 index 0000000..d727757 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/CHANGELOG.rst @@ -0,0 +1,25 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +1.0.5 (2020-01-10) +------------------ +* bugfix compilation problem on posix systems without timeout features + +0.61.4 (2015-10-10) +------------------- +* fix long standing bug in mutex tests on the build farm - skip deadlock tests in release mode + +0.61.1 (2015-07-22) +------------------- +* don't detach an ecl thread that hasn't been started + +0.61.0 (2014-09-12) +------------------- +* const'ness for appropriate thread functions + +0.60.6 (2014-01-29) +------------------- +* update to catkin's CFG_EXTRAS for easy to find cmake modules. +* remove cmake debug message. +* Contributors: Daniel Stonier diff --git a/ros2_ws/src/ecl_core/ecl_threads/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/CMakeLists.txt new file mode 100644 index 0000000..3430306 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/CMakeLists.txt @@ -0,0 +1,68 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_threads) + +############################################################################## +# Thread Detection +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_concepts REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_time REQUIRED) +find_package(ecl_utilities REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() +ecl_detect_threads() + +if(ECL_PLATFORM_HAS_POSIX_THREADS) + # TODO: move this over into ecl_detect_threads + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) + set (thread_INTERFACE "Threads::Threads" CACHE STRING "Platform thread interface") +else() + set (thread_INTERFACE "" CACHE STRING "Platform thread interface") +endif() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors + ecl_concepts + ecl_exceptions + ecl_time + ecl_utilities +) +ament_package(CONFIG_EXTRAS "${PROJECT_NAME}-extras.cmake") diff --git a/ros2_ws/src/ecl_core/ecl_threads/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_threads/doxygen/mainpage.dox new file mode 100644 index 0000000..5875587 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/doxygen/mainpage.dox @@ -0,0 +1,236 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section Package Summary + + Threads are not defined in standard C++ and as a result are operating system + and platform dependant. Linux generally uses POSIX threads, which are also + available on windows, but the WIN32 API is usually preferred. Because of this, some + standard cross-platform interfaces are developed here. + +@section Features + + - Mutex - multi-thread variable protection. + - Threads - raii style one-shot thread class. + - Threadable - an inheritable thread interface. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that uses + these container classes. + @code + #include + + // The thread classes + using ecl::Mutex; + using ecl::Thread; + using ecl::Threadable; + + // Priorities + using ecl::set_priority; + using ecl::get_priority; + using ecl::print_priority_diagnostics; + using ecl::BackgroundPriority; + using ecl::LowPriority; + using ecl::NormalPriority; + using ecl::HighPriority; + using ecl::CriticalPriority; + using ecl::RealTimePriority1; + using ecl::RealTimePriority2; + using ecl::RealTimePriority3; + using ecl::RealTimePriority4; + @endcode + +You will also need to link to -lecl_threads. + +@section Usage + + @subsection Mutex + + The mutex is fairly standard, and on some systems can be more complex, but here the wrapper + simply acts as a closed door with the usual lock, trylock and unlock features. + The behaviour is also somewhat different depending on the platform. + + On posix, the class is set up to run in two modes. When NDEBUG is not defined, it will + do exception handling (via ecl's StandardException) + for posix errors as well as configuring the mutexes for deadlock + checking (see below for example code). Exception handling and deadlock checking are disabled + when NDEBUG is defined. + + @code + Mutex mutex; + + mutex.lock(); // Locks + // do work here + mutex.unlock(); + mutex.trylock(); // Locks + mutex.trylock(); // Fails to lock and returns immediately. + mutex.unlock(); + + + mutex.lock(); + // mutex.lock(); // The DEADLOCK! Like this, the program will usually halt forever. + + // If NDEBUG is not defined, then on posix systems, you can catch deadlocks like this. + try { + mutex.lock(); + } catch ( StandardException &e ) { + std::cout << e.what() << std::endl; + } + + // Typical output from a caught deadlock: + // Location : /mnt/froody/work/code/cpp/projects/ecl/modules/core/src/lib/threads/mutex_pos.cpp:57 + // Flag : The object was used incorrectly. + // Detail : DEADLOCK! The mutex has already been locked by this thread, it now has to wait on itself. + @endcode + + @subsection Priorities + + These can be configured via the ecl::set_priority() function using the ecl::Priority + enum values as an abstraction to a platform's implementation (which varies + quite significantly from platform to platform). Check the documentation's + api for further details on its usage, particularly for posix which complicates + things with both userland priorities and real time priorities. + + @subsection Thread + + The @ref ecl::Thread "Thread" class is a raii style object which initialises and automatically + starts a thread when constructed and manages the thread cleanly when the thread object goes out of scope. + + Construction: + + Construction can be done directly through free and member function handles or via function objects. Refer + to the documentation on 'Function Objects' and 'Reference Wrappers' in ecl_utilities + for more details about creating and using function objects/reference + wrappers (note, use a reference wrapper if you want to pass a 'heavy' function object!). + + @code + using ecl::utilities::generateFunctionObject; + + int f() {} + int g(int i) {} + class A { + void f() {} + void g(int i) {} + }; + class FunctionObject { + public: + typedef void result_type; + void operator()() { // + } + }; + // ... + A a; + FunctionObject function_object; + + Thread thread1(f)); // Thread a nullary global function. + Thread thread2(generateFunctionObject(g, 3)); // Thread a bound unary global function. + Thread thread3(&A::f, a); // Thread a nullary member function. + Thread thread4(generateFunctionObject(&A::g, a, 2)); // Thread a bound unary member function. + Thread thread5(function_object); // Thread a nullary function object. + Thread thread6(ref(function_object)); // Thread a reference to a nullary function object. + @endcode + + Scope: + + Also, this object is permitted to go out of scope without affecting the thread that it started (it may very well still + be running!). When it goes out of scope, it simply detaches it and lets it clean itself up. At this point you + only lose control of administration of the thread (joining, checking if it is running, cancelling etc). + + @code + void g() { + for (int i = 0; i < 10; ++i ) { + sleep(1); + cout << i << endl; + } + } + + void create_out_of_scope_thread() { + Thread thread(g); + } // thread will go out of scope here. + // ... + create_out_of_scope_thread(); + // Cannot manage the thread from here, but it will continue running. + sleep(10); // Note that we have no way of joining with it. + @endcode + + Thread Priority: + + Thread priorities can be specified at construction (ecl::Thread) or at the call to + execute a Threadable (Threadable::start()). This will impose the specified + priority for scheduling for the lifetime of the thread. + + If you wish to configure the thread's priority dynamically, you'll have to + fall back to using the ecl::set_priority() function directly from inside the + worker function. + + Stack Size: + + On embedded systems with no swap its important to watch how much stack memory you supply to the thread. This can be + manually specified in the thread constructor. + + @code + Thread thread(g,1024*1024); // allocates 1M to the thread instead of the system default which is usually 8M. + @endcode + + Other: + + Other member functions include + - cancel() : instructs a running thread to abort at the next permitted interruption point (read the man pages for pthreads for more info). + - join() : wait for the running thread to finish. + - isRunning() : check to see if the thread is still running. + + Error handling is done in debug mode (i.e. -DNDEBUG is not set) via exceptions. These will throw and report any information on + the resulting posix errors should they occur. + + @subsection Threadable + + The threadable class implements a concept is for worker threads that want to retain state + information (possibly for use by other parts of the program) in a class. Think of it as + a threaded function object rather than a regular c-style threaded function. + + + Implementation wise, it provides an inheritable interface for your + threading class. All the class needs to do is: + + - inherit the Threadable class. + - implement the runnable() method. + - call the start() method to begin running in a sepearate thread. + + Note that it will not spawn multiple threads - it has a check that ensures it will + only execute one thread at any point in time. It is designed to be something + more akin to a thread function object rather than a thread factory. + + @code + class A : Threadable { + void runnable() { + // thread work here + } + } + + int main() { + A a; + a.start(); + return 0; + } + @endcode + +\section unitTests Unit Tests + + - src/test/mutex.cpp + - src/test/threads.cpp + - src/test/threadable.cpp + +@section ChangeLog + + - May 11 : Updated exception handling (now optional). + - May 10 : Mutex win32 implementation. + - May 10 : Cmake win32 framework. + - Jan 10 : @ref ecl::Threadable "Threadable" implements the thread by inheritance concept. + - Jan 10 : Adds a constructor for @ref ecl::Thread "threads" that allows configuration of the stack size allocation. + - Jul 09 : Incorporates the use of function object loading (refer to ecl_utilities). + - Jul 09 : Converted @ref ecl::Thread "threads" to raii style. + - Jun 09 : A locking class, the @ref ecl::Mutex "mutex", for threads. + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_threads/doxygen/namespaces.dox new file mode 100644 index 0000000..43e5e07 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/doxygen/namespaces.dox @@ -0,0 +1,15 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::threads + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/ecl_threads-extras.cmake b/ros2_ws/src/ecl_core/ecl_threads/ecl_threads-extras.cmake new file mode 100644 index 0000000..331b173 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/ecl_threads-extras.cmake @@ -0,0 +1,9 @@ + +find_package(ecl_build REQUIRED) + +ecl_detect_threads() + +if(ECL_PLATFORM_HAS_POSIX_THREADS) + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..231d9a2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(threads) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads.hpp new file mode 100644 index 0000000..f35c0a0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads.hpp @@ -0,0 +1,49 @@ +/** + * @file /include/ecl/threads.hpp + * + * @brief Cross-platform threading interfaces. + * + * Threads are modelled here as classes. The threading functionality can be + * utilised in two ways, either via inheritance or composition. Choice of which + * is simply a matter of personal style. There are more complex thread managers + * out there, but this suits the requirements of a small project and merely + * aims to provide a robust and lightweight cross-platform interface. + * + * @date June, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_HPP_ +#define ECL_THREADS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/* + * Guard against the qt macros. + */ +#ifdef emit + #undef emit + #define replace_qt_emit +#endif + +//#include "threads/barrier.hpp" +#include "threads/mutex.hpp" +#include "threads/priority.hpp" +#include "threads/thread.hpp" +#include "threads/threadable.hpp" + +#ifdef replace_qt_emit + #define emit +#endif + + + +#endif /* ECL_THREADS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/CMakeLists.txt new file mode 100644 index 0000000..1788248 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +FILE(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +INSTALL(FILES ${HEADERS} DESTINATION include/ecl/threads) + diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/macros.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/macros.hpp new file mode 100644 index 0000000..4494310 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/threads/macros.hpp + * + * @brief Macros for ecl threads. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_MACROS_HPP_ +#define ECL_THREADS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_threads_EXPORTS // we are building a shared lib/dll + #define ecl_threads_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_threads_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_threads_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_threads_PUBLIC + #define ecl_threads_LOCAL +#endif + +#endif /* ECL_THREADS_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex.hpp new file mode 100644 index 0000000..820d19f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex.hpp @@ -0,0 +1,32 @@ +/** + * @file /include/ecl/threads/mutex.hpp + * + * @brief Mutex interface. + * + * Cross-platform mutex for locking/unlocking shared memory in a + * multi-threaded application. In linux it uses pthreads, in windows it + * uses critical sections. + * + * @date June 2009 + **/ +#ifndef ECL_ECL_THREADS_MUTEX_HPP_ +#define ECL_ECL_THREADS_MUTEX_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/************************************************************************* + * Includes + ************************************************************************/ + +#if defined(ECL_HAS_POSIX_THREADS) + #include "mutex_pos.hpp" +#elif defined(ECL_HAS_WIN32_THREADS) + #include "mutex_w32.hpp" +#endif + + +#endif /* ECL_ECL_THREADS_MUTEX_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_pos.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_pos.hpp new file mode 100644 index 0000000..99335dc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_pos.hpp @@ -0,0 +1,292 @@ +/** + * @file /include/ecl/threads/mutex_pos.hpp + * + * @brief Posix interface for a mutex. + * + * @date June 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_MUTEX_POS_HPP_ +#define ECL_THREADS_MUTEX_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include // strerror function +#include +#include +#include +#include +#include +#include +#include + + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +typedef pthread_mutex_t RawMutex; /**< @brief Abstraction representing the fundamental mutex type. **/ + +/***************************************************************************** +** Class Mutex +*****************************************************************************/ +/** + * @brief Cross-platformable lock for shared memory access in a single application.. + * + * This class provides an object that handles locking/unlocking memory between + * threads in the same process. It uses the posix mutex which can be configured + * in a variety of ways. For convenience, this mutex class is configured so + * that it uses exception handling for errors (including deadlock checking!) when -DNDEBUG is not + * present. At some stage later I may set global/local mechanisms for enabling + * deadlock checking on mutex's if it proves to be a neccessary feature, but for + * now, its kept simple and as automatic as possible. + * + * One other feature of posix mutexes is that you can set priorities for them, + * but I have not done that here. + * + * On linux they are handled in the kernel, so they are fast + * and schedulers can be set up to optimise how they are handled. + * + * Error handling + * + * In debug mode, all of the mutex's operations will throw if an error occurs. In + * addition, posix will attempt to detect deadlocks (and ecl will subsequently throw + * an exception) while in debug mode. + * + * For release mode, there is no flag to check if a mutex is running (generally this + * is pretty foolproof *or* you have a deadlock and can't do anything anyway. I could + * provide a graceful fallback with an error flag, but will only do so if really + * necessary. + **/ +class Mutex { +public: + /** + * @brief Initialises the mutex. + * + * Assigns the required resources for the mutex. This also automatically + * configures the mutex to check for deadlocks if NDEBUG is not defined. + * + * @param locked : optionally lock the mutex upon creation (default is unlocked). + * + * @exception StandardException : throws if mutex initialisation fails [debug mode only]. + */ + Mutex(const bool locked = false); + /** + * @brief Destroys the mutex. + * + * De-allocates the resources allocated to the mutex. + */ + virtual ~Mutex(); + + /** + * @brief Unlocks the mutex. + * + * @exception StandardException : throws if mutex unlocking fails [debug mode only]. + */ + void unlock(); + /** + * @brief Locks the mutex. + * + * @exception StandardException : throws if mutex locking fails [debug mode only]. + */ + void lock(); + /** + * @brief Attempts to lock the mutex, but will timeout if it fails for a certain duration. + * + * Attempts to lock the mutex, but will timeout if it fails for a certain duration. + * + * Note: this function is not always available on posix systems (e.g. macosx). + * When it is not present, it will simply default its behaviour to that of a + * regular trylock(). + * + * @return bool : success or failure of the attempt to lock the mutex. + * + * @exception StandardException : throws if mutex timed locking fails [debug mode only]. + */ + bool trylock(Duration &duration); + /** + * @brief Tries to lock, but returns immediately if it can't. + * + * Like its counterpart lock(), but it won't wait around if the + * mutex is already locked. + * + * @return bool : success or failure of the attempt to lock the mutex. + * + * @exception StandardException : throws if mutex trylock recorded an error other than an already busy mutex [debug mode only]. + */ + bool trylock(); + /** + * @brief Number of threads that have this mutex currently locked. + * + * This represents the number of threads currently associated with + * this mutex. There can only be at most 1 accessing, with the rest + * are currently waiting for their turn. + * + * @return unsigned int : the number of locks currently associated with this mutex. + **/ + unsigned int locks() { return number_locks; } + + /** + * @brief Accesses the system-dependent fundamental mutex type. + * + * Returns a reference to the underlying mutex type. + * @return RawMutex& : a reference to the underlying mutex type. + */ + RawMutex& rawType() { return mutex; } + +private: + RawMutex mutex; + unsigned int number_locks; + +}; + +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions] +*****************************************************************************/ + +#if defined(ECL_HAS_EXCEPTIONS) +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [Mutex Exceptions] +*****************************************************************************/ + +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutexattr_init calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexAttrException(const char* loc, int error_result) { + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The specified mutex attribute was invalid."); + case ( ENOMEM ) : return StandardException(loc, MemoryError, "There is insufficient memory for initialisation of the mutex attribute."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutex_init calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexInitException(const char* loc, int error_result) { + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The specified mutex was invalid."); + case ( EBUSY ) : return StandardException(loc, InvalidInputError, "The mutex object has already been initialised and not yet destroyed."); + case ( EAGAIN ) : return StandardException(loc, MemoryError, "The mutex object has already been initialised and not yet destroyed."); + case ( ENOMEM ) : return StandardException(loc, MemoryError, "There is insufficient memory for initialisation of the mutex."); + case ( EPERM ) : return StandardException(loc, PermissionsError, "The user does not have the privilege to perform the operation."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutex_destroy calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexDestroyException(const char* loc, int error_result) { + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, DestructorError, "The specified mutex is invalid (for some reason or other)."); + case ( EBUSY ) : return StandardException(loc, DestructorError, "Attempted to destroy the mutex while it was locked."); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutex_timedlock calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexTimedLockException(const char* loc, int error_result) { + switch (error_result) { + case ( EDEADLK ): return StandardException(loc, UsageError, "DEADLOCK! The current thread already owns the mutex."); + // These aren't relevant to us (EBUSY is normal operation for trylock, EINVAL can't happen because of RAII, and EAGAIN because our mutex isn't RECURSIVE) + case ( EINVAL ) : return StandardException(loc, UsageError, "The mutex is not initialised or it is priority protected and the calling thread's priority is higher than the mutex' current priority ceiling."); + case ( EAGAIN ) : return StandardException(loc, OutOfRangeError, "The mutex could not be acquired because the maximum number of recursive locks for the mutex has been exceeded."); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutex_lock/trylock calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexLockException(const char* loc, int error_result) { + switch (error_result) { + case ( EDEADLK ): return StandardException(loc, UsageError, "DEADLOCK! The mutex has already been locked by this thread, it now has to wait on itself."); + // These aren't relevant to us (EBUSY is normal operation for trylock, EINVAL can't happen because of RAII, and EAGAIN because our mutex isn't RECURSIVE) + case ( EBUSY ) : return StandardException(loc, ConfigurationError, "The try lock failed because it was already locked (normal operation really, not really an error)."); + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The mutex does not refer to an initialised mutex."); + case ( EAGAIN ) : return StandardException(loc, OutOfRangeError, "The mutex could not be acquired because the maximum number of recursive locks for the mutex has been exceeded."); + default : return StandardException(loc, PosixError, "Unknown error."); + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_mutex_unock calls within + * the Mutex class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : mutex functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the execption to throw. + */ +inline StandardException ECL_LOCAL throwMutexUnLockException(const char* loc, int error_result) { + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The mutex does not refer to an initialised mutex."); + case ( EAGAIN ) : return StandardException(loc, OutOfRangeError, "The mutex could not be acquired because the maximum number of recursive locks for the mutex has been exceeded."); + case ( EPERM ) : return StandardException(loc, PermissionsError, "The user does not have the privilege to perform the operation."); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} + + +} // namespace threads +} // namespace ecl + +#endif /* ECL_HAS_EXCEPTIONS */ +#endif /* ECL_IS_POSIX */ +#endif /* ECL_THREADS_MUTEX_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_w32.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_w32.hpp new file mode 100644 index 0000000..db3a9e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/mutex_w32.hpp @@ -0,0 +1,137 @@ +/** + * @file /ecl_threads/include/ecl/threads/mutex_w32.hpp + * + * @brief File comment + * + * File comment + * + * @date 27/05/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_MUTEX_W32_HPP_ +#define ECL_THREADS_MUTEX_W32_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "macros.hpp" + + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Typedefs +*****************************************************************************/ + +typedef CRITICAL_SECTION RawMutex; /**< @brief Abstraction representing the fundamental mutex type. **/ + +/***************************************************************************** +** Class Mutex +*****************************************************************************/ +/** + * @brief Cross-platformable lock for shared memory access in a single application.. + * + * This is a very simple implementation of the win32 mutex using + * CRITICAL_SECTION objects. It slightly lacks in functionality compared + * to the posix mutex's - there's no debug deadlock checking mode and there + * is no timed trylock functionality either. However, it works and the same + * interface is used across platforms (the timed trylock defaults to an + * ordinary trylock). + **/ +class ecl_threads_PUBLIC Mutex { +public: + /** + * @brief Initialises the mutex. + * + * Assigns the required resources for the mutex. + * + * @param locked : optionally lock the mutex upon creation (default is unlocked). + */ + Mutex(const bool locked = false); + /** + * @brief Destroys the mutex. + * + * De-allocates the resources allocated to the mutex. + */ + virtual ~Mutex(); + + /** + * @brief Unlocks the mutex. + * + * Unlocks the mutex. + */ + void unlock(); + /** + * @brief Locks the mutex. + * + * Locks the mutex. + */ + void lock(); + /** + * @brief Attempts to lock the mutex, but will timeout if it fails for a certain duration. + * + * Attempts to lock the mutex, but will timeout if it fails for a certain duration. + * + * Note: this function is not available on win32 systems. + * In order to maintain a standard interface, it will simply default + * its behaviour to that of a regular trylock(). + * + * @return bool : success or failure of the attempt to lock the mutex. + */ + bool trylock(Duration &duration); + /** + * @brief Tries to lock, but returns immediately if it can't. + * + * Like its counterpart lock(), but it won't wait around if the + * mutex is already locked. + * + * @return bool : success or failure of the attempt to lock the mutex. + */ + bool trylock(); + /** + * @brief Number of threads that have this mutex currently locked. + * + * This represents the number of threads currently associated with + * this mutex. There can only be at most 1 accessing, with the rest + * are currently waiting for their turn. + * + * @return unsigned int : the number of locks currently associated with this mutex. + **/ + unsigned int locks() { return number_locks; } + + /** + * @brief Accesses the system-dependent fundamental mutex type. + * + * Returns a reference to the underlying mutex type. + * @return RawMutex& : a reference to the underlying mutex type. + */ + RawMutex& rawType() { return mutex; } + +private: + RawMutex mutex; + unsigned int number_locks; + +}; + +} // namespace ecl + + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_THREADS_MUTEX_W32_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority.hpp new file mode 100644 index 0000000..9aa3174 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority.hpp @@ -0,0 +1,29 @@ +/** + * @file /include/ecl/threads/priority.hpp + * + * @brief Priority scheduling for threads. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_PRIORITY_HPP_ +#define ECL_THREADS_PRIORITY_HPP_ + +/***************************************************************************** +** Cross Platform Implementation +*****************************************************************************/ + +#include // ECL_ macros + +#include "priority_common.hpp" +#if defined(ECL_IS_POSIX) + #include "priority_pos.hpp" +#elif defined(ECL_HAS_WIN32_THREADS) + #include "priority_win.hpp" +#endif + + +#endif /*ECL_THREADS_PRIORITY_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_common.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_common.hpp new file mode 100644 index 0000000..6e50007 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_common.hpp @@ -0,0 +1,49 @@ +/** + * @file /include/ecl/threads/priority_common.hpp + * + * @brief Common types for priority scheduling. + * + * @date January 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_PRIORITY_COMMON_HPP_ +#define ECL_THREADS_PRIORITY_COMMON_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Common types +*****************************************************************************/ + +/** + * @brief Shared abstraction of the scheduling priorities. + * + * Defines a priority level for priority scheduling of a thread/process. + * They are effectively ranked as indicated, however their + * implementation will be different for different systems. + */ +enum Priority { + DefaultPriority = 0, + UnknownPriority, + BackgroundPriority, + LowPriority, + NormalPriority, + HighPriority, + CriticalPriority, + RealTimePriority1, + RealTimePriority2, + RealTimePriority3, + RealTimePriority4, +}; + + +} // namespace ecl + +#endif /*ECL_THREADS_PRIORITY_COMMON_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_pos.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_pos.hpp new file mode 100644 index 0000000..5e50d61 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_pos.hpp @@ -0,0 +1,222 @@ +/** + * @file /include/ecl/threads/priority_pos.hpp + * + * @brief Posix priority scheduling. + * + * @date May 2009. + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_PRIORITY_POS_HPP_ +#define ECL_THREADS_PRIORITY_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "priority_common.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Sets the priority to the specified level. + * + * Posix scheduling has several policies (cf. windows which has only one), + * we only use two. + * + * - SCHED_OTHER : the traditional priority group. + * - SCHED_RR : a real time priority group. + * + * The traditional policy group uses 'niceness' to weight process scheduling + * with a standard automatic scheduler as seen on most systems. The ecl + * Priority levels that are spread across this weighting system include + * (from lowest priority to highest) : + * + * - BackgroundPriority + * - LowPriority + * - NormalPriority + * - HighPriority + * - CriticalPriority + * + * The real time priority group elevates processes above the traditional + * group, so the scheduler will always allow the realtime priority process + * to work before a traditional priority process. These too are given + * priority levels (usually 1-99), so that higher level priorities + * will similarly dominate lower level priorities. Threads with the same + * realtime priority will be put into a round-robin. The ecl Priority + * levels that are spread across the realtime group include (from lowest to + * highest priority): + * + * Be careful with the realtime priorities as it will cause the current + * process to dominate processes with lesser priorities (i.e. potentially locking + * up the machine or starving other threads/processes). + * + * - RealTimePriority1 + * - RealTimePriority2 + * - RealTimePriority3 + * - RealTimePriority4 + * + * One further note, higher level priorities cannot be enabled by a normal + * user on a linux system (usually anything higher than NormalPriority). You have + * several options in this case: + * - Run the binary as root. + * - Unlock the SYS_CAP_NICE posix file capability on the binary (not possible yet on linux systems). + * - Edit the user's limits in /etc/security/limits.conf. + * + * An example of editing this file for a user snorri to enable both realtime priorities + * to level 95 and the maximum niceness setting on a typical linux box: + * @code + * snorri - nice -20 + * snorri - rtprio 95 + * @endcode + * + * You can observe the process' prioritisation via the ps command. A useful set of flags + * that lets you determine rt priority/niceness and a few other vitals is (see man ps for more + * details): + * + * @code + * ps -C -m -o pid,rtprio,ni,pri,vsize,rssize,pmem,pcpu,comm + * @endcode + * + * @param priority_level : the priority level requested for this process. + * @return bool : true if success, false if failed and exceptions aren't enabled. + * @exception StandardException : throws if configuration fails. + */ +bool ECL_PUBLIC set_priority(Priority priority_level); +/** + * @brief Returns the process' current priority level. + * + * @return Priority : the process priority enumeration (UnknownPriority if it fails and exceptions aren't enabled). + * @exception StandardException : if exceptions enabled, throws if the call fails. + */ +Priority ECL_PUBLIC get_priority(); + +/** + * @brief Print priority diagnostics to a string. + * @return string : insert into a stream to display/log. + * @exception StandardException : if exceptions enabled, throws if any call fails. + */ +std::string ECL_PUBLIC print_priority_diagnostics(); + +/***************************************************************************** +** Namespace +*****************************************************************************/ + +namespace threads { + +/** + * @brief Worker function to configure the real time priorities. + * + * Configures the process with real time scheduling and prioritisation. + * + * Warning: the specified level will be ignored if you are using PAM and + * it is larger than the user's specified rtprio limit. In this case, it + * defaults back to its parent's priority. + * + * @param policy : either SCHED_OTHER or SCHED_RR. + * @param priority_level : a value converted from one of the PriorityLevel abstractions. + * @return bool : true if it works, false if not (or unsupported). + * + * @exception StandardException : if exceptions are enabled, throws if the operation fails or is not supported. + */ +bool ECL_LOCAL set_real_time_priority(int policy,int priority_level); + +} // namespace threads +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions] +*****************************************************************************/ + +#if defined(ECL_HAS_EXCEPTIONS) +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [Priority Exceptions] +*****************************************************************************/ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by priority function calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by usleep and nanosleep posix + * functions used in the sleeper classes. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +inline StandardException ECL_LOCAL throwPriorityException(const char* loc ) { + int error_result = errno; + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, ecl::InvalidInputError, "The specified param structure or priority group was invalid."); + case ( ESRCH ) : return StandardException(loc, ecl::InvalidInputError, "The process specified could not be found."); + case ( EPERM ) : return StandardException(loc, ecl::PermissionsError, "The caller does not have the appropriate privileges for realtime scheduling (http://snorriheim.dnsdojo.com/doku/doku.php/en:linux:admin:priorities)."); + case ( EACCES ) : return StandardException(loc, ecl::PermissionsError, "The caller does not have the appropriate privileges for elevating the process priority by reducing the niceness value (http://snorriheim.dnsdojo.com/doku/doku.php/en:linux:admin:priorities)."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + + +} // namespace threads +} // namespace ecl +#endif /* ECL_HAS_EXCEPTIONS */ +#endif /* ECL_IS_POSIX */ +#endif /* ECL_THREADS_PRIORITY_POS_HPP_ */ + + +// void yield(); +// void capabilities() throw(StandardException); + + +///* +// * Yields this process (must be a real-time process) to lower priority processes. +// * In effect, this places the process at the back of the cpu queue, even if there +// * are lower priority processes ahead of it. +// */ +//inline void Process::yield() +//{ +// sched_yield(); +//} + +///* +// * Print out the posix capabilities of your program. +// */ +//inline void Process::capabilities() throw(StandardException) +//{ +// cap_t cap = cap_get_proc(); +// +// if (!cap) { +// throw StandardException(LOC,"Could not retrieve posix characteristics.","Was not possible to retrieve the processes' posix capability list."); +// } +// std::cout << "Posix capabilities " << cap_to_text(cap,NULL) << std::endl; +// cap_free(cap); +//} + diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_win.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_win.hpp new file mode 100644 index 0000000..35e2a55 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/priority_win.hpp @@ -0,0 +1,151 @@ +/** + * @file /include/ecl/threads/priority_win.hpp + * + * @brief Priority scheduling for Windows. + * + * @date April 2013. + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_PRIORITY_WIN_HPP_ +#define ECL_THREADS_PRIORITY_WIN_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "priority_common.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Sets the priority of current thread. + * + * The ecl Priority levels that are spread across this weighting system include + * (from lowest priority to highest) : + * + * - BackgroundPriority + * - LowPriority + * - NormalPriority + * - HighPriority + * - CriticalPriority + * + * The real time priority group is treated one - time critical priority + * + * - RealTimePriority1 + * - RealTimePriority2 + * - RealTimePriority3 + * - RealTimePriority4 + * + * @param priority_level : the priority level requested for this process. + * @return bool : true if success, false if failed and exceptions aren't enabled. + * @exception StandardException : throws if configuration fails. + */ +bool ecl_threads_PUBLIC set_priority(Priority priority_level); +/** + * @brief Returns the priority of current thread. + * + * @return Priority : the process priority enumeration (UnknownPriority if it fails and exceptions aren't enabled). + * @exception StandardException : if exceptions enabled, throws if the call fails. + */ +Priority ecl_threads_PUBLIC get_priority(); + +/** + * @brief Print priority diagnostics to a string. + * @return string : insert into a stream to display/log. + * @exception StandardException : if exceptions enabled, throws if any call fails. + */ +std::string ecl_threads_PUBLIC print_priority_diagnostics(); + +/***************************************************************************** +** Namespace +*****************************************************************************/ + +namespace threads { + +/** + * @brief Worker function to configure the real time priorities. + * + * Configures the process with real time scheduling and prioritisation. + * + * Warning: the specified level will be ignored if you are using PAM and + * it is larger than the user's specified rtprio limit. In this case, it + * defaults back to its parent's priority. + * + * @param policy : either SCHED_OTHER or SCHED_RR. + * @param priority_level : a value converted from one of the PriorityLevel abstractions. + * @return bool : true if it works, false if not (or unsupported). + * + * @exception StandardException : if exceptions are enabled, throws if the operation fails or is not supported. + */ +bool ECL_LOCAL set_real_time_priority(int policy,int priority_level); + +} // namespace threads +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions] +*****************************************************************************/ + +#if defined(ECL_HAS_EXCEPTIONS) +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [Priority Exceptions] +*****************************************************************************/ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by priority function calls. + * + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by usleep and nanosleep posix + * functions used in the sleeper classes. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +inline StandardException ECL_LOCAL throwPriorityException(const char* loc ) { + int error_result = errno; + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, ecl::InvalidInputError, "The specified param structure or priority group was invalid."); + case ( ESRCH ) : return StandardException(loc, ecl::InvalidInputError, "The process specified could not be found."); + case ( EPERM ) : return StandardException(loc, ecl::PermissionsError, "The caller does not have the appropriate privileges for realtime scheduling (http://snorriheim.dnsdojo.com/doku/doku.php/en:linux:admin:priorities)."); + case ( EACCES ) : return StandardException(loc, ecl::PermissionsError, "The caller does not have the appropriate privileges for elevating the process priority by reducing the niceness value (http://snorriheim.dnsdojo.com/doku/doku.php/en:linux:admin:priorities)."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } +} + + +}; // namespace threads +} // namespace ecl +#endif /* ECL_HAS_EXCEPTIONS */ +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_THREADS_PRIORITY_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread.hpp new file mode 100644 index 0000000..b1e987f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread.hpp @@ -0,0 +1,35 @@ +/** + * @file /include/ecl/threads/thread.hpp + * + * @brief Thread interfaces. + * + * Cross-platform thread functionality to be used as a composited variable (i.e, + * not an inheritable interface). + * + * @date June 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_THREAD_HPP_ +#define ECL_THREADS_THREAD_HPP_ + +/************************************************************************* + * Includes + ************************************************************************/ + +#include + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#if defined(ECL_HAS_POSIX_THREADS) + #include "thread_pos.hpp" +#elif defined(ECL_HAS_WIN32_THREADS) + #include "thread_win.hpp" +#endif + + +#endif /* ECL_THREADS_THREAD_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_exceptions_pos.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_exceptions_pos.hpp new file mode 100644 index 0000000..11f78aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_exceptions_pos.hpp @@ -0,0 +1,130 @@ +/** + * @file /include/ecl/threads/thread_exceptions_pos.hpp + * + * @brief Exception handlers for pthreads. + * + * @date Jun 30, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_THREAD_EXCEPTIONS_POS_HPP_ +#define ECL_THREADS_THREAD_EXCEPTIONS_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [Errors] +*****************************************************************************/ +/** + * This function generates the required ecl Error response + * for posix error numbers generated by pthread_create calls. + * + * @param error_result : thread functions do not use errno, so we must pass this function result directly to the handler. + * @return Error : the appropriate standardised ecl Error response. + */ +inline Error ECL_LOCAL handlePthreadCreateError(int error_result) { + switch (error_result) { + case ( EINVAL ) : return Error(InvalidInputError); + case ( EAGAIN ) : return Error(MemoryError); + case ( EPERM ) : return Error(PermissionsError); + default : return Error(UnknownError); + } +} +} // namespace threads +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions] +*****************************************************************************/ + +#include +#if defined(ECL_HAS_EXCEPTIONS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { + +/***************************************************************************** +** Functions +*****************************************************************************/ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_create calls. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : thread functions do not use errno, so we must pass this function result directly to the handler. + * @return StandardException : the appropriate ecl standardised exception. + */ +inline StandardException ECL_LOCAL throwPthreadCreateException(const char* loc, int error_result) { + switch (error_result) { + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "Invalid settings in 'attr'"); + case ( EAGAIN ) : return StandardException(loc, MemoryError, "Insufficient resources to create another thread."); + case ( EPERM ) : return StandardException(loc, PermissionsError, "No permission to set the scheduling policy and parameters specified in attr."); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} + +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_create calls. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : thread functions do not use errno, so we must pass this function result directly to the handler. + */ +inline StandardException ECL_LOCAL throwPthreadJoinException(const char* loc, int error_result) { + switch (error_result) { + case ( EDEADLK ) : return StandardException(loc, UsageError, "Deadlock! Two threads tried to join each other or a thread tried to join itself."); + case ( EINVAL ) : return StandardException(loc, InvalidInputError, "The specified thread is not joinable or another thread is already waiting to join with it."); + case ( ESRCH ) : return StandardException(loc, InvalidInputError, "The specified thread (id) could not be found. Probably its already been joined?"); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} +/** + * This function generates a custom StandardException response + * for posix error numbers generated by pthread_cancel calls. + * @param loc : use with the LOC macro, identifies the line and file of the code. + * @param error_result : thread functions do not use errno, so we must pass this function result directly to the handler. + */ +inline StandardException ECL_LOCAL throwPthreadCancelException(const char* loc, int error_result) { + switch (error_result) { + case ( ESRCH ) : return StandardException(loc, InvalidInputError, "The specified thread (id) could not be found. Probably its already terminated."); + default : return StandardException(loc, UnknownError, "Unknown error."); + } +} + +} // namespace threads +} // namespace ecl + +#endif /* ECL_HAS_EXCEPTIONS */ +#endif /* ECL_IS_POSIX */ +#endif /* ECL_THREADS_THREAD_EXCEPTIONS_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_pos.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_pos.hpp new file mode 100644 index 0000000..fe01f7b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_pos.hpp @@ -0,0 +1,501 @@ +/** + * @file /include/ecl/threads/thread_pos.hpp + * + * @brief Posix interface for the thread class. + * + * @date June 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_THREAD_POS_HPP_ +#define ECL_THREADS_THREAD_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "thread_exceptions_pos.hpp" +#include +#include +#include +#include +#include +#include "priority_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [ThreadTask] +*****************************************************************************/ +/** + * @brief Psuedo-mechanism for creating ThreadTask objects in @ref ecl::Thread "Thread". + * + * Used by the thread class for creating ThreadTask objects on the heap. Not intended + * for direct use. + */ +class ECL_LOCAL ThreadTaskBase { +public: + virtual ~ThreadTaskBase() {}; + +protected: + ThreadTaskBase(const Priority& priority) : priority_level(priority) {}; /**< This constructor is only enabled for child ThreadTask classes. **/ + ecl::Priority priority_level; +}; +/** + * @brief The thread task template family. + * + * Stores all the functional information needed by a posix thread to start, run and + * carry through to completion. Used by the @ref ecl::Thread "Thread" class and + * not intended for direct use. + * + * @tparam F : the nullary function object type to be run inside the thread. + */ +template +class ECL_LOCAL ThreadTask : public ThreadTaskBase { +public: + /** + * @brief Initialises the class with a nullary function object. + * + * Initialises the class with a nullary function object. + * + * @param f : the nullary function. + * @param priority : the priority level for the thread task. + */ + ThreadTask(const F &f, const Priority &priority) : ThreadTaskBase(priority), function(f) { + ecl_compile_time_concept_check(ecl::NullaryFunction); + }; + virtual ~ThreadTask() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief Posix thread function wrapper. + * + * This static function enables member functions to be run by the posix_thread_create function. + * It's a simple trick that will automatically get used by the @ref ecl::Thread "Thread" + * class - don't worry about using this method directly. + * + * @param ptr_this : a pointer to an instance of this class. + * @return void* : a posix thread requirement, the return value (unused). + */ + static void* EntryPoint(void *ptr_this) { + ThreadTask< F, false > *ptr = static_cast< ThreadTask< F, false > * >(ptr_this); + ecl::set_priority(ptr->priority_level); + (ptr->function)(); + delete ptr; + ptr_this = NULL; + return ptr_this; + } + +private: + F function; +}; + +/** + * @brief Specialisation of the thread tasks, this one handles reference wrappers to funciton objects. + * + * Stores all the referenced functional information needed by a posix thread to start, run and + * carry through to completion. Used by the @ref ecl::Thread "Thread" class and + * not intended for direct use. + * + * @tparam F : the nullary function object referenced and run inside the thread. + */ +template +class ECL_LOCAL ThreadTask : public ThreadTaskBase { +public: + /** + * @brief Initialises the class with a nullary function object. + * + * Initialises the class with a nullary function object. + * + * @param f : the nullary function. + * @param priority : the priority level for the thread task. + */ + ThreadTask(const F &f, const Priority &priority) : ThreadTaskBase(priority), function(f.reference()) { + ecl_compile_time_concept_check(ecl::NullaryFunction< typename F::type>); + }; + virtual ~ThreadTask() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief Posix thread function wrapper. + * + * This static function enables member functions to be run by the posix_thread_create function. + * It's a simple trick that will automatically get used by the @ref ecl::Thread "Thread" + * class - don't worry about using this method directly. + * + * @param ptr_this : a pointer to an instance of this class. + * @return void* : a posix thread requirement, the return value (unused). + */ + static void* EntryPoint(void *ptr_this) { + ThreadTask< F, true > *ptr = static_cast< ThreadTask< F, true > * >(ptr_this); + ecl::set_priority(ptr->priority_level); + (ptr->function)(); + delete ptr; + ptr_this = NULL; + return ptr_this; + } + +private: + typename F::type &function; +}; + +} // namespace threads + +/***************************************************************************** +** Interface [Thread] +*****************************************************************************/ +/** + * @brief Posix thread class. + * + * This is a simple one-shot thread class that uses the principle of RAII. + * Once constructed, the thread immediately starts and any cleanup is taken + * care of by the destructor. + * + * Usage: + * + * Initialise with a nullary function object or one of the convenience + * constructors for global/static and member functions. + * + * @code + using ecl::generateFunctionObject; + + int f() {} + int g(int i) {} + class A { + void f() {} + void g(int i) {} + }; + class FunctionObject { + public: + typedef void result_type; + void operator()() { // + } + }; + // ... + A a; + FunctionObject function_object; + + Thread thread1(f)); // Thread a nullary global function. + Thread thread2(generateFunctionObject(g, 3)); // Thread a bound unary global function. + Thread thread3(&A::f, a); // Thread a nullary member function. + Thread thread4(generateFunctionObject(&A::g, a, 2)); // Thread a bound unary member function. + Thread thread5(function_object); // Thread a nullary function object. + Thread thread6(ref(function_object)); // Thread a reference to a nullary function object. + @endcode + + Note that you must ensure that the instance (in the above example, 'a') must not go out + * of scope while the thread is running. To keep it lightweight, it does not copy the class to the thread, + * merely includes a reference to it. + * + * One important usage point, you may allow the thread instance to go out of + * scope without affecting the created thread - this simply detaches the + * thread so you can no longer administer it, but it will continue running + * in the background. + * + @code + void g() { + for (int i = 0; i < 10; ++i ) { + sleep(1); + cout << i << endl; + } + } + + void create_out_of_scope_thread() { + Thread thread(g); + } // thread will go out of scope here. + // ... + create_out_of_scope_thread(); + // Cannot adminster the thread from here, but it will continue running. + sleep(10); // Note that we have no way of joining with it. + @endcode + + Error Handling + + These threads are RAII style - error handling is done with the constructor which will throw exceptions + in debug mode only (too much of a slowdown to do so in release mode if many threads are required). + + If exceptions are turned off or you are in release mode, isRunning() can be checked to verify that + the thread is running as expected. + */ +class ECL_PUBLIC Thread { +public: + /** + * @brief Default constructor that doesn't automatically start the thread. + * + * This is useful sometimes when you need to delay the start of the thread + * execution (to wait on some initialisation parameters for example). + * Use one of the start() functions to kick the thread off. + */ + Thread() : + thread_task(NULL), + has_started(false), + join_requested(false) + { + (void) schedule_parameters; + } + /** + * @brief Convenience constructor that starts a new thread with a void global/static function. + * + * This provides an easy construction format for void global/static functions. + * It essentially emulates the call made by the more general function + * object constructor: + * + * Usage: + * @code + * void f() {} + * // ... + * Thread thread(f); + * @endcode + * + * @param function : a void function pointer, void (*)(). + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + Thread(VoidFunction function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts the thread if not already started. + * + * @param function : a void function pointer, void (*)(). + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + Error start(VoidFunction function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Convenience method that starts a new thread utilising a void member function. + * + * This provides an easy construction format for void member functions. + * It essentially emulates the call made by the more general function + * object constructor: + * + * Usage: + * @code + * class A { + * void f() {} + * }; + * // ... + * A a; + * Thread thread(&A::f, a); + * @endcode + * + * @param function : the member function. + * @param c : the member function's class instance. + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + template + Thread(void (C::*function)(), C &c, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts the thread if not already started. + * + * @param function : the member function. + * @param c : the member function's class instance. + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + template + Error start(void (C::*function)(), C &c, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + + /** + * @brief Starts a new thread utilising a nullary function object. + * + * Starts a new thread with the specified nullary function object. You can create your + * own custom nullary functions, or utilise the generateFunctionObject method from ecl_utilities + * to bind/generate them. + * + * Usage: + @code + int f(int i) {} + class A { + void f() {} + void g(int i) {} + }; + class FunctionObject { + public: + typedef void result_type; + void operator()() { // + } + }; + // ... + A a; + FunctionObject function_object; + Thread thread0(generateFunctionObject(f, 3)); // Bind the first argument to a global function + Thread thread1(generateFunctionObject(&A::f, a)); // Generate a typical member function + Thread thread2(generateFunctionObject(&A::g, a, 2)); // Bind the first argument to a member function + Thread thread3(function_object); // Nullary function object (uses operator()()) + Thread thread4(ref(function_object)); // Thread a reference to a nullary function object. + @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the NullaryFunction concept (refer to the ecl_concepts package). + * + * @param function : the nullary function object. + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + template + Thread(const F &function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts a new thread utilising a nullary function object. + * + * @param function : the nullary function object. + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + template + Error start(const F &function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + + /** + * @brief Cleans up the resources allocated to the thread. + * + * If not already joined, this ensures the thread resources are cleaned up when the thread + * object goes out of scope. Note that this will not terminate the actual running thread ( + * if the running thread is actually still running), rather it simply detaches and loses + * administrative control over it. + */ + virtual ~Thread(); + + /** + * @brief Check to see if the thread is still running. + * + * @return bool : true if the thread task is still running, false otherwise. + */ + bool isRunning() const { if ( thread_task == NULL ) { return false; } else { return true; } } + + /** + * @brief Queue a cancel request for this thread to abort. + * + * This commands sends a request to the thread for cancellation. The calling thread + * will not wait, it merely queues the request and then keeps processing. The running + * thread will also keep processing, but will cancel as soon as it reaches its next + * cancellation point. + * + * Threads can be setup to deny cancel requests, but this class always configures them as + * cancellable. Create another class if you wish to use this functionality of posix threads. + * + * Further, a posix thread's cancellation type can be asynchronous, but here we use the + * deferred status, which means it will look for a suitable cancellation point. These are + * safe points in the code (usually defined by sleep functions and similar functions in your + * c library implementation - see posix man pages for a complete list on your distribution). + * + * @exception StandardException : throws if this thread is no longer running [debug mode only]. + */ + void cancel(); + + /** + * @brief Join with this thread. + * + * This command causes the calling thread to halt up and wait for the running thread to + * finish. + * @exception StandardException : throws if this thread is no longer running [debug mode only]. + */ + void join(); + + +private: + pthread_t thread_handle; + pthread_attr_t attrs; + sched_param schedule_parameters; + threads::ThreadTaskBase *thread_task; + bool has_started; + bool join_requested; + + void initialise(const long &stack_size); + + enum ThreadProperties { + DefaultStackSize = -1 + }; +}; + +/***************************************************************************** +** Template Implementation [Thread] +*****************************************************************************/ + +template +Thread::Thread(void (C::*function)(), C &c, const Priority &priority, const long &stack_size) : + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, c, priority, stack_size); + +} + +template +Thread::Thread(const F &function, const Priority &priority, const long &stack_size) : + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, priority, stack_size); +} + +template +Error Thread::start(void (C::*function)(), C &c, const Priority &priority, const long &stack_size) +{ + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + initialise(stack_size); + thread_task = new threads::ThreadTask< BoundNullaryMemberFunction >(generateFunctionObject( function, c ), priority); + int result = pthread_create(&(this->thread_handle), &(this->attrs), threads::ThreadTask< BoundNullaryMemberFunction >::EntryPoint, thread_task); + pthread_attr_destroy(&attrs); + if ( result != 0 ) { + delete thread_task; + thread_task = NULL; + ecl_debug_throw(threads::throwPthreadCreateException(LOC,result)); + return threads::handlePthreadCreateError(result); // if in release mode, gracefully fall back to return values. + } + return Error(NoError); +} + +template +Error Thread::start(const F &function, const Priority &priority, const long &stack_size) +{ + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + initialise(stack_size); + thread_task = new threads::ThreadTask::value >(function, priority); + int result = pthread_create(&(this->thread_handle), &(this->attrs), threads::ThreadTask::value>::EntryPoint, thread_task); + pthread_attr_destroy(&attrs); + if ( result != 0 ) { + delete thread_task; + thread_task = NULL; + ecl_debug_throw(threads::throwPthreadCreateException(LOC,result)); + return threads::handlePthreadCreateError(result); // if in release mode, gracefully fall back to return values. + } + return Error(NoError); +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_THREADS_THREAD_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_win.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_win.hpp new file mode 100644 index 0000000..860ee94 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/thread_win.hpp @@ -0,0 +1,560 @@ +/** + * @file /include/ecl/threads/thread_win.hpp + * + * @brief Win32 interface for the thread class. + * + * @date April 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_THREAD_WIN_HPP_ +#define ECL_THREADS_THREAD_WIN_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "thread_exceptions_pos.hpp" +#include +#include +#include +#include +#include +#include "priority_win.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { + +/***************************************************************************** +** Interface [ThreadTask] +*****************************************************************************/ +/** + * @brief Psuedo-mechanism for creating ThreadTask objects in @ref ecl::Thread "Thread". + * + * Used by the thread class for creating ThreadTask objects on the heap. Not intended + * for direct use. + */ +class ECL_LOCAL ThreadTaskBase { +public: + virtual ~ThreadTaskBase() {}; + +protected: + ThreadTaskBase(const Priority& priority) : priority_level(priority) {}; /**< This constructor is only enabled for child ThreadTask classes. **/ + ecl::Priority priority_level; +}; +/** + * @brief The thread task template family. + * + * Stores all the functional information needed by a posix thread to start, run and + * carry through to completion. Used by the @ref ecl::Thread "Thread" class and + * not intended for direct use. + * + * @tparam F : the nullary function object type to be run inside the thread. + */ +template +class ECL_LOCAL ThreadTask : public ThreadTaskBase { +public: + /** + * @brief Initialises the class with a nullary function object. + * + * Initialises the class with a nullary function object. + * + * @param f : the nullary function. + * @param priority : the priority level for the thread task. + */ + ThreadTask(const F &f, const Priority &priority) : ThreadTaskBase(priority), function(f) { + ecl_compile_time_concept_check(ecl::NullaryFunction); + }; + virtual ~ThreadTask() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief Win32 thread function wrapper. + * + * This static function enables member functions to be run by the CreateThread function. + * It's a simple trick that will automatically get used by the @ref ecl::Thread "Thread" + * class. + * + * @param ptr_this : a pointer to an instance of this class. + * @return unsigned int : a Win32 thread requirement, the return value. + */ + static unsigned int EntryPoint(void *ptr_this) { + ThreadTask< F, false > *ptr = static_cast< ThreadTask< F, false > * >(ptr_this); + (ptr->function)(); + return 0; + } + +private: + F function; +}; + +/** + * @brief Specialisation of the thread tasks, this one handles reference wrappers to funciton objects. + * + * Stores all the referenced functional information needed by a posix thread to start, run and + * carry through to completion. Used by the @ref ecl::Thread "Thread" class and + * not intended for direct use. + * + * @tparam F : the nullary function object referenced and run inside the thread. + */ +template +class ECL_LOCAL ThreadTask : public ThreadTaskBase { +public: + /** + * @brief Initialises the class with a nullary function object. + * + * Initialises the class with a nullary function object. + * + * @param f : the nullary function. + * @param priority : the priority level for the thread task. + */ + ThreadTask(const F &f, const Priority &priority) : ThreadTaskBase(priority), function(f.reference()) { + ecl_compile_time_concept_check(ecl::NullaryFunction< typename F::type>); + }; + virtual ~ThreadTask() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief Win32 thread function wrapper. + * + * This static function enables member functions to be run by the CreateThread function. + * It's a simple trick that will automatically get used by the @ref ecl::Thread "Thread" class + * + * @param ptr_this : a pointer to an instance of this class. + * @return unsigned int : a Win32 thread requirement. the return value. + */ + static unsigned int EntryPoint(void *ptr_this) { + ThreadTask< F, true > *ptr = static_cast< ThreadTask< F, true > * >(ptr_this); + (ptr->function)(); + return 0; + } + +private: + typename F::type &function; +}; + +}; // namespace threads + +/***************************************************************************** +** Interface [Thread] +*****************************************************************************/ +/** + * @brief Win32 thread class. + * + * This is a simple one-shot thread class that uses the principle of RAII. + * Once constructed, the thread immediately starts and any cleanup is taken + * care of by the destructor. + * + * Usage: + * + * Initialise with a nullary function object or one of the convenience + * constructors for global/static and member functions. + * + * @code + using ecl::generateFunctionObject; + + int f() {} + int g(int i) {} + class A { + void f() {} + void g(int i) {} + }; + class FunctionObject { + public: + typedef void result_type; + void operator()() { // + } + }; + // ... + A a; + FunctionObject function_object; + + Thread thread1(f)); // Thread a nullary global function. + Thread thread2(generateFunctionObject(g, 3)); // Thread a bound unary global function. + Thread thread3(&A::f, a); // Thread a nullary member function. + Thread thread4(generateFunctionObject(&A::g, a, 2)); // Thread a bound unary member function. + Thread thread5(function_object); // Thread a nullary function object. + Thread thread6(ref(function_object)); // Thread a reference to a nullary function object. + @endcode + + Note that you must ensure that the instance (in the above example, 'a') must not go out + * of scope while the thread is running. To keep it lightweight, it does not copy the class to the thread, + * merely includes a reference to it. + * + * One important usage point, you may allow the thread instance to go out of + * scope without affecting the created thread - this simply detaches the + * thread so you can no longer administer it, but it will continue running + * in the background. + * + @code + void g() { + for (int i = 0; i < 10; ++i ) { + sleep(1); + cout << i << endl; + } + } + + void create_out_of_scope_thread() { + Thread thread(g); + } // thread will go out of scope here. + // ... + create_out_of_scope_thread(); + // Cannot adminster the thread from here, but it will continue running. + sleep(10); // Note that we have no way of joining with it. + @endcode + + Error Handling + + These threads are RAII style - error handling is done with the constructor which will throw exceptions + in debug mode only (too much of a slowdown to do so in release mode if many threads are required). + + If exceptions are turned off or you are in release mode, isRunning() can be checked to verify that + the thread is running as expected. + */ +class ecl_threads_PUBLIC Thread { +public: + /** + * @brief Default constructor that doesn't automatically start the thread. + * + * This is useful sometimes when you need to delay the start of the thread + * execution (to wait on some initialisation parameters for example). + * Use one of the start() functions to kick the thread off. + */ + Thread() : + thread_handle(NULL), + thread_task(NULL), + has_started(false), + join_requested(false) + {} + /** + * @brief Convenience constructor that starts a new thread with a void global/static function. + * + * This provides an easy construction format for void global/static functions. + * It essentially emulates the call made by the more general function + * object constructor: + * + * Usage: + * @code + * void f() {} + * // ... + * Thread thread(f); + * @endcode + * + * @param function : a void function pointer, void (*)(). + * @param priority : set the priority level for the thread. + * @param stack_size : no. of bytes to allocate on the stack (default is to use the system value, usually 8k). + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + Thread(VoidFunction function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts the thread if not already started. + * + * @param function : a void function pointer, void (*)(). + * @param priority : set the priority level for the thread. + * @param stack_size : ignored, currently not available. + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + Error start(VoidFunction function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Convenience method that starts a new thread utilising a void member function. + * + * This provides an easy construction format for void member functions. + * It essentially emulates the call made by the more general function + * object constructor: + * + * Usage: + * @code + * class A { + * void f() {} + * }; + * // ... + * A a; + * Thread thread(&A::f, a); + * @endcode + * + * @param function : the member function. + * @param c : the member function's class instance. + * @param priority : set the priority level for the thread. + * @param stack_size : ignored, currently not available. + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + template + Thread(void (C::*function)(), C &c, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts the thread if not already started. + * + * @param function : the member function. + * @param c : the member function's class instance. + * @param priority : set the priority level for the thread. + * @param stack_size : ignored, currently not available. + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + template + Error start(void (C::*function)(), C &c, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + + /** + * @brief Starts a new thread utilising a nullary function object. + * + * Starts a new thread with the specified nullary function object. You can create your + * own custom nullary functions, or utilise the generateFunctionObject method from ecl_utilities + * to bind/generate them. + * + * Usage: + @code + int f(int i) {} + class A { + void f() {} + void g(int i) {} + }; + class FunctionObject { + public: + typedef void result_type; + void operator()() { // + } + }; + // ... + A a; + FunctionObject function_object; + Thread thread0(generateFunctionObject(f, 3)); // Bind the first argument to a global function + Thread thread1(generateFunctionObject(&A::f, a)); // Generate a typical member function + Thread thread2(generateFunctionObject(&A::g, a, 2)); // Bind the first argument to a member function + Thread thread3(function_object); // Nullary function object (uses operator()()) + Thread thread4(ref(function_object)); // Thread a reference to a nullary function object. + @endcode + * + * This will emit a compile time failure if the template argument does + * not conform to the NullaryFunction concept (refer to the ecl_concepts package). + * + * @param function : the nullary function object. + * @param priority : set the priority level for the thread. + * @param stack_size : ignored, currently not available. + * @exception StandardException : throws if thread creation fails [debug mode only]. + */ + template + Thread(const F &function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + /** + * @brief Starts a new thread utilising a nullary function object. + * + * @param function : the nullary function object. + * @param priority : set the priority level for the thread. + * @param stack_size : ignored, currently not available. + * @exception StandardException : throws if thread creation fails [debug mode only]. + * @return Error : error result, fallback for when exceptions aren't available. + */ + template + Error start(const F &function, const Priority &priority = DefaultPriority, const long &stack_size = -1 ); + + /** + * @brief Cleans up the resources allocated to the thread. + * + * If not already joined, this ensures the thread resources are cleaned up when the thread + * object goes out of scope. Note that this will not terminate the actual running thread ( + * if the running thread is actually still running), rather it simply detaches and loses + * administrative control over it. + */ + virtual ~Thread(); + + /** + * @brief Check to see if the thread is still running. + * + * @return bool : true if the thread task is still running, false otherwise. + */ + bool isRunning() { if ( thread_task == NULL ) { return false; } else { return true; } } + + /** + * @brief Queue a cancel request for this thread to abort. + * + * This commands sends a request to the thread for cancellation. The calling thread + * will not wait, it merely queues the request and then keeps processing. The running + * thread will also keep processing, but will cancel as soon as it reaches its next + * cancellation point. + * + * Threads can be setup to deny cancel requests, but this class always configures them as + * cancellable. + * + * @exception StandardException : throws if this thread is no longer running [debug mode only]. + */ + void cancel(); + + /** + * @brief Join with this thread. + * + * This command causes the calling thread to halt up and wait for the running thread to + * finish. + * @exception StandardException : throws if this thread is no longer running [debug mode only]. + */ + void join(); + + +private: + HANDLE thread_handle; + threads::ThreadTaskBase *thread_task; + bool has_started; + bool join_requested; + + void initialise(const long &stack_size); + + enum ThreadProperties { + DefaultStackSize = -1 + }; +}; + +/***************************************************************************** +** Template Implementation [Thread] +*****************************************************************************/ + +template +Thread::Thread(void (C::*function)(), C &c, const Priority &priority, const long &stack_size) : + thread_handle(NULL), + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, c, priority, stack_size); + +} + +template +Thread::Thread(const F &function, const Priority &priority, const long &stack_size) : + thread_handle(NULL), + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, priority, stack_size); +} + +template +Error Thread::start(void (C::*function)(), C &c, const Priority &priority, const long &stack_size) +{ + // stack_size is ignored + + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + + thread_task = new threads::ThreadTask< BoundNullaryMemberFunction >(generateFunctionObject( function, c ), priority); + + DWORD threadid; + + thread_handle = CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)threads::ThreadTask< BoundNullaryMemberFunction >::EntryPoint, + thread_task, + 0, + &threadid); + + if (!thread_handle) { + ecl_debug_throw(StandardException(LOC, UnknownError, "Failed to create thread.")); + return Error(UnknownError); + } + + BOOL bResult = FALSE; + + if (priority >= RealTimePriority1) { + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL); + } + + switch (priority) { + case CriticalPriority: + bResult = SetThreadPriority(thread_handle, HIGH_PRIORITY_CLASS); + break; + case HighPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_ABOVE_NORMAL); + break; + case LowPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_BELOW_NORMAL); + break; + case BackgroundPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE); + break; + default: + break; + } + + if (!bResult) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + } + + return Error(NoError); +} + +template +Error Thread::start(const F &function, const Priority &priority, const long &stack_size) +{ + // stack_size is ignored + + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + + thread_task = new threads::ThreadTask::value >(function, priority); + + DWORD threadid; + + thread_handle = CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)threads::ThreadTask::value >::EntryPoint, + thread_task, + 0, + &threadid); + + if (!thread_handle) { + ecl_debug_throw(StandardException(LOC, UnknownError, "Failed to create thread.")); + return Error(UnknownError); + } + + BOOL bResult = FALSE; + + if (priority >= RealTimePriority1) { + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL); + } + + switch (priority) { + case CriticalPriority: + bResult = SetThreadPriority(thread_handle, HIGH_PRIORITY_CLASS); + break; + case HighPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_ABOVE_NORMAL); + break; + case LowPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_BELOW_NORMAL); + break; + case BackgroundPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE); + break; + default: + break; + } + + if (!bResult) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + } + + return Error(NoError); +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_THREADS_THREAD_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/threadable.hpp b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/threadable.hpp new file mode 100644 index 0000000..1f90eb4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/include/ecl/threads/threadable.hpp @@ -0,0 +1,107 @@ +/** + * @file /include/ecl/threads/threadable.hpp + * + * @brief Posix version of the threadable interfaces. + * + * Posix threadable functionality to be used as an inherited interface. + * For a composited interface, use the Thread class. + * + * @date January 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_THREADS_THREADABLE_POS_HPP_ +#define ECL_THREADS_THREADABLE_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "thread.hpp" +#include "priority.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Threadable] +*****************************************************************************/ +/** + * @brief An inheritable interface for starting threads. + * + * This concept is for worker threads that want to retain state information + * (possibly for use by other parts of the program) in a class. This is often + * a convenient structure for c++ oriented threaded programs. + * + * Implementation wise, it provides an inheritable interface for your + * threading class. All the class needs to do is: + * + * - inherit the Threadable class. + * - implement the runnable() method. + * - call the start() method to begin running in a sepearate thread. + * + * Note that it will not spawn multiple threads - it has a check that ensures it will + * only execute one thread at any point in time. It is designed to be something + * more akin to a thread function object rather than a thread factory. + * + * However, once the threaded work is finished, you may start the worker + * thread once more. + * + * @sa @ref ecl::Thread "Thread". + */ +class ECL_PUBLIC Threadable { +public: + virtual ~Threadable() {} + + /** + * @brief Begin execution of the worker thread. + * + * This begins execution of the implemented virtual runnable() in a separate thread. + * Note that it makes a check first to see if a thread is already running and simply + * returns if there is. There can be only one! + * + * @return bool : true if started, false if a worker thread is already running. + */ + bool start(const Priority &priority = DefaultPriority) { + if ( isRunning() ) { return false; } + isRunning(true); // This is not ideal, as it's not perfectly atomic (i.e. someone can query isRunning before this gets set). + Thread thread(&Threadable::executeThreadFunction,*this, priority); + return true; + } + /** + * @brief Used to check if a worker thread is already running. + * + * Use this to check if a worker thread is already running. + */ + Parameter isRunning; + +protected: + Threadable() : isRunning(false) {} + + virtual void runnable() = 0; + +private: + void executeThreadFunction() { + runnable(); + isRunning(false); + } +}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_THREADS_THREADABLE_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/package.xml b/ros2_ws/src/ecl_core/ecl_threads/package.xml new file mode 100644 index 0000000..13907e7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/package.xml @@ -0,0 +1,47 @@ + + + ecl_threads + 1.2.1 + + This package provides the c++ extensions for a variety of threaded + programming tools. These are usually different on different + platforms, so the architecture for a cross-platform framework + is also implemented. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_threads + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_concepts + ecl_exceptions + ecl_time + ecl_utilities + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_concepts + ecl_exceptions + ecl_time + ecl_utilities + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/src/CMakeLists.txt new file mode 100644 index 0000000..e9bf667 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + +add_subdirectory(examples) diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/src/examples/CMakeLists.txt new file mode 100644 index 0000000..059b70a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/examples/CMakeLists.txt @@ -0,0 +1,23 @@ +############################################################################## +# Macros +############################################################################## + +macro(ecl_threads_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries( + ecl_demo_${name} + PUBLIC + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_time::ecl_time + ) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################## +# Executables +############################################################################## + +ecl_threads_add_demo(thread) +ecl_threads_add_demo(mutex) diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/examples/mutex.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/examples/mutex.cpp new file mode 100644 index 0000000..d0eefa6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/examples/mutex.cpp @@ -0,0 +1,99 @@ +/** + * @file src/examples/mutex.cpp + * + * @brief Demos the mutex functions. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/threads/mutex.hpp" +#include "../../include/ecl/threads/thread.hpp" +#include + +int shared_value = 0; +ecl::Mutex mutex; + +void f() { + ecl::Sleep sleep; + sleep(1); + + std::cout << "Thread: enter blocking" << std::endl; + mutex.lock(); + + shared_value = 10; + std::cout << "Thread: sets shared_value to 10" << std::endl; + + mutex.unlock(); + std::cout << "Thread: leave blocking" << std::endl; +} + +int main() { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Mutex" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Lock" << std::endl; + mutex.lock(); + + std::cout << "Unlock" << std::endl; + mutex.unlock(); + + std::cout << "Trylock" << std::endl; + mutex.trylock(); + + std::cout << "Try to lock block already locked" << std::endl; + if (mutex.trylock()) { + std::cout << "Abnormal" << std::endl; + } else { + std::cout << "Failed(Normal)" << std::endl; + } + + std::cout << "Unlock" << std::endl; + mutex.unlock(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Synchronization" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::Thread thread_f(f); + ecl::Sleep sleep; + + std::cout << "Main: enter blocking" << std::endl; + mutex.lock(); + sleep(3); + + if (shared_value < 5) { + std::cout << "shared_value(" << shared_value << ") is smaller than 5" << std::endl; + } else { + std::cout << "shared_value(" << shared_value << ") is larger than 5" << std::endl; + } + + mutex.unlock(); + std::cout << "Main: leave blocking" << std::endl; + + thread_f.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/examples/thread.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/examples/thread.cpp new file mode 100644 index 0000000..cd7ba2a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/examples/thread.cpp @@ -0,0 +1,168 @@ +/** + * @file src/examples/thread.cpp + * + * @brief Demos the thread functions. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/threads/thread.hpp" +#include + +class ThreadMemberFunctions { +public: + void f() { + std::cout << "A::f()" << std::endl; + } + void g(const int &i) { + std::cout << "A::g(" << i << ")" << std::endl; + } +}; + +class NullaryFunction { +public: + NullaryFunction() : i(0) {}; + typedef void result_type; + void operator()() { + for (int j = 0; j < 3; ++j ) { + std::cout << " Nullary Function Object: " << i << std::endl; + ecl::Sleep sleep; + sleep(1); + ++i; + } + std::cout << " Nullary Function Object: finished." << std::endl; + } + int i; +}; + +void d() { + for (int i = 0; i < 5; ++i ) { + ecl::Sleep sleep; + sleep(1); + std::cout << " d(): " << i << std::endl; + } + std::cout << " d(): finished" << std::endl; +} +void d_cb() { + std::cout << " d(): callback function" << std::endl; +} + +void f() { + for (int i = 0; i < 3; ++i) { + std::cout << "f(): " << i << std::endl; + } +} + +void g(const int &i) { + for (int j = 0; j < 3; ++j) { + std::cout << "g(" << i << ")" << std::endl; + } +} + +void deconstructThread() { + ecl::Thread thread_deconstruct(d); +} + +int main() { + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Thread Function Type" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ThreadMemberFunctions a; + ecl::Thread thread_f1(f); + ecl::Thread thread_f2(&ThreadMemberFunctions::f, a); + ecl::Thread thread_f3(ecl::generateFunctionObject(f)); + ecl::Thread thread_f4(ecl::generateFunctionObject(g,1)); + ecl::Thread thread_f5(ecl::generateFunctionObject(&ThreadMemberFunctions::f,a)); + ecl::Thread thread_f6(ecl::generateFunctionObject(&ThreadMemberFunctions::g,a,2)); + + thread_f1.join(); + thread_f2.join(); + thread_f3.join(); + thread_f4.join(); + thread_f5.join(); + thread_f6.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Cancel" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::Thread thread(ecl::generateFunctionObject(d)); + ecl::Sleep sleep; + sleep(3); + if (!thread.isRunning()) { + std::cout << "Abnormal #1" << std::endl; + } + thread.cancel(); + if (thread.isRunning()) { + std::cout << "Abnormal #2" << std::endl; + } + thread.join(); + if (thread.isRunning()) { + std::cout << "Abnormal #3" << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Deconstruct" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + deconstructThread(); + sleep(6); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Nullary Function Objects" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + NullaryFunction function_object_1; + ecl::Thread thread_f8(function_object_1); + sleep(4); + ecl::Thread thread_f9(ecl::ref(function_object_1)); + sleep(4); + thread_f8.join(); + thread_f9.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Delayed Start" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + NullaryFunction function_object_2; + ThreadMemberFunctions b; + ecl::Thread thread1, thread2, thread3, thread4; + thread1.start(f); + thread2.start(function_object_2); + thread3.start(&ThreadMemberFunctions::f,b); + thread4.start(ecl::generateFunctionObject(&ThreadMemberFunctions::g,b,2)); + + thread1.join(); + thread2.join(); + thread3.join(); + thread4.join(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/src/lib/CMakeLists.txt new file mode 100644 index 0000000..ce88d4b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/CMakeLists.txt @@ -0,0 +1,43 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_concepts::ecl_concepts + ecl_config::ecl_config + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_time::ecl_time + ecl_utilities::ecl_utilities + ${thread_INTERFACE} +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_pos.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_pos.cpp new file mode 100644 index 0000000..6f81844 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_pos.cpp @@ -0,0 +1,122 @@ +/** + * @file /src/lib/mutex_pos.cpp + * + * @brief Posix mutex implementation. + * + * @date June 2009 + **/ +/***************************************************************************** + ** Platform Check + *****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include "../../include/ecl/threads/mutex.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl { + +/***************************************************************************** + * Mutex Class Methods + *****************************************************************************/ + +Mutex::Mutex(const bool locked) : + number_locks(0) +{ + + pthread_mutexattr_t attr; + int result; + + result = pthread_mutexattr_init(&attr); + ecl_assert_throw(result == 0, threads::throwMutexAttrException(LOC,result)); + + #if defined(NDEBUG) || defined(ECL_NDEBUG) + result = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_NORMAL); + #else + result = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); + #endif + ecl_assert_throw(result == 0, threads::throwMutexAttrException(LOC,result)); + + if (result == 0) { + result = pthread_mutex_init(&mutex, &attr); + } + ecl_assert_throw(result == 0, threads::throwMutexInitException(LOC,result)); + result = pthread_mutexattr_destroy(&attr); + ecl_assert_throw(result == 0, threads::throwMutexAttrException(LOC,result)); + + if (locked) { + this->lock(); + } +} + +Mutex::~Mutex() +{ + pthread_mutex_destroy(&mutex); + // Spank! Destructor exceptions are bad. + // ecl_assert_throw( result == 0, threads::throwMutexDestroyException(LOC,result)); +} + +void Mutex::lock() +{ + ++number_locks; + int result = pthread_mutex_lock(&mutex); + ecl_assert_throw(result == 0, threads::throwMutexLockException(LOC,result)); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +bool Mutex::trylock(Duration &duration) +{ + #if defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS - 200112L) >= 0L + timespec timeout; + timeout.tv_sec = duration.sec(); + timeout.tv_nsec = duration.nsec(); + int result = pthread_mutex_timedlock(&mutex, &timeout); + if (result == ETIMEDOUT) { + return false; + } + ecl_assert_throw(result == 0, threads::throwMutexTimedLockException(LOC,result)); + ++number_locks; + #else + (void) duration; + return trylock(); // fallback option + #endif + return true; +} + +bool Mutex::trylock() +{ + int result = pthread_mutex_trylock(&mutex); + + // result will typically be EBUSY if already locked, so filter it from the assert check. + if (result == EBUSY) { + return false; + } + + ecl_assert_throw(result == 0, threads::throwMutexLockException(LOC,result)); + + // If we made it here, it means the attempt locked the mutex. + ++number_locks; + return true; +} + +void Mutex::unlock() +{ + --number_locks; + int result = pthread_mutex_unlock(&mutex); + ecl_assert_throw(result == 0, threads::throwMutexUnLockException(LOC,result)); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_w32.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_w32.cpp new file mode 100644 index 0000000..0dbe43c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/mutex_w32.cpp @@ -0,0 +1,67 @@ +/** + * @file /ecl_threads/src/lib/mutex_w32.cpp + * + * @brief Win32 mutex implementation. + * + * @date May 2010 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/threads/mutex_w32.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +* Mutex Class Methods +*****************************************************************************/ + +Mutex::Mutex(const bool locked) : number_locks(0) { + InitializeCriticalSection(&mutex); // has no return value + if ( locked ) { + this->lock(); + } +} + +Mutex::~Mutex() { + DeleteCriticalSection(&mutex); // has no return value +} + +void Mutex::lock() { + InterlockedIncrement((long*)&number_locks); + EnterCriticalSection(&mutex); // has no return value +} + +bool Mutex::trylock(Duration &duration) { + return trylock(); +} + +bool Mutex::trylock() { + if (number_locks > 0) + return false; + lock(); + return true; +} + +void Mutex::unlock() +{ + LeaveCriticalSection( &mutex ); + InterlockedDecrement((long*)&number_locks); +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_pos.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_pos.cpp new file mode 100644 index 0000000..83d974e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_pos.cpp @@ -0,0 +1,340 @@ +/** + * @file /src/lib/priority_pos.cpp + * + * @brief Posix priority configuration implementation. + * + * @date May 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/threads/priority_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::ostringstream; + +/***************************************************************************** +** Implementation [Process] +*****************************************************************************/ + +bool set_priority(Priority priority_level) +{ + /************************************************************************* + * Real time priority exception. Run this with absolute priority rather + * than the 'niceness' values. We use Round Robin scheduling here, the + * alternative is Fifo so we can get some automatic scheduling if we + * want it. + * + * Priority levels usually range from 1 to 99, but we map them virtually + * to system built-ins just in case. The virtual map only uses a few + * levels of priority as shown below. + * + * RealTimePriority1 = priority_min [lowest] + * RealTimePriority2 = priority_min + priority_range/10 + * RealTimePriority3 = priority_min + 2*priority_range/10 + * RealTimePriority4 = priority_min + 3*priority_range/10 [highest] + * + *************************************************************************/ + if ( priority_level >= RealTimePriority1 ) { + #if _POSIX_PRIORITY_SCHEDULING > 0 + int rr_min = sched_get_priority_min(SCHED_RR); int rr_max = sched_get_priority_max(SCHED_RR); + if ( ( rr_min == -1 ) || (rr_max == -1) ) { + ecl_throw(StandardException(LOC,NotSupportedError,"The posix SCHED_RR policy is not available on this system [sched_get_priority_min/max].")); + return false; + } + ecl_try { + // usually exception will put it into a catch, otherwise we return false if it fails. + if ( !threads::set_real_time_priority(SCHED_RR,rr_min+(priority_level - RealTimePriority1)*(rr_max - rr_min)/10) ) { + return false; + } + } ecl_catch(StandardException &e ) { + ecl_throw(StandardException(e)); // Rethrow + } + #else + ecl_throw(StandardException(LOC,NotSupportedError,"Your version of posix does not support real time priority scheduling for process management.")); + return false; + #endif + return true; + } + + /************************************************************************* + ** Regular priority levels using 'niceness'. Lower values usually give + ** the process higher importance (-20 to 20 usually). This is an + ** indicator to the scheduler on how to bias the process's dynamic + ** scheduling priority which can be seen when you do a 'top'. + *************************************************************************/ + int return_value = 0; + + switch (priority_level) { + case CriticalPriority : { + return_value = setpriority(PRIO_PROCESS,0,PRIO_MIN); + break; + } + case HighPriority : { + setpriority(PRIO_PROCESS,0,PRIO_MIN + (PRIO_MAX-PRIO_MIN)/4); + break; + } + case NormalPriority : { + setpriority(PRIO_PROCESS,0,PRIO_MIN + (PRIO_MAX-PRIO_MIN)/2); + break; + } + case LowPriority : { + setpriority(PRIO_PROCESS,0,PRIO_MIN + 3*(PRIO_MAX-PRIO_MIN)/4); + break; + } + case BackgroundPriority : { + setpriority(PRIO_PROCESS,0,PRIO_MAX); + break; + } + default : { + // RealTimePriority# already handled, Default and Unknown -> do nothing. + break; + } + } + if ( return_value == -1 ) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return false; + } + return true; +} + +Priority get_priority() +{ + /****************************************** + ** Check for Scheduling Policy (Trad/RT) + *******************************************/ + #if _POSIX_PRIORITY_SCHEDULING > 0 + int scheduler = sched_getscheduler(0); + switch ( scheduler ) { + case ( -1 ) : { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return UnknownPriority; + break; + } + case ( SCHED_OTHER ) : { + // We just want the niceness, get it outside of this switch. + break; + } + case ( SCHED_RR ) : { // Realtime priorities. + /****************************************** + ** Check RealTime Priority Level + *******************************************/ + sched_param param; + if ( sched_getparam(0,¶m) != 0 ) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return UnknownPriority; + } + int rr_min = sched_get_priority_min(SCHED_RR); + int rr_max = sched_get_priority_max(SCHED_RR); + if ( ( rr_min == -1 ) || (rr_max == -1) ) { + ecl_throw(StandardException(LOC,NotSupportedError,"The posix SCHED_RR policy is not available on this system [sched_get_priority_min/max].")); + return UnknownPriority; + } + if ( param.sched_priority >= rr_min + 3*(rr_max-rr_min)/10 ) { + return RealTimePriority4; + } else if ( param.sched_priority >= rr_min + 2*(rr_max-rr_min)/10 ) { + return RealTimePriority3; + } else if ( param.sched_priority >= rr_min + (rr_max-rr_min)/10 ) { + return RealTimePriority2; + } else { + return RealTimePriority1; + } + break; + } + case ( SCHED_FIFO ) : { return UnknownPriority; } // We dont use this one. + #if defined(SCHED_BATCH) // Didn't turn up on an old gcc3 with an arm pax270 board. + case ( SCHED_BATCH ) : { return UnknownPriority; } // We dont use this one. + #endif + default : { return UnknownPriority; } // Shouldn't ever reach here, but we might pick up new policies that we dont use here. + } + #endif + /****************************************** + ** Check traditional priority niceness + *******************************************/ + switch ( getpriority(PRIO_PROCESS,0) ) { + case (PRIO_MIN) : { return CriticalPriority; } + case (PRIO_MIN + (PRIO_MAX-PRIO_MIN)/4) : { return HighPriority; } + case (PRIO_MIN + (PRIO_MAX-PRIO_MIN)/2) : { return NormalPriority; } + case (PRIO_MIN + 3*(PRIO_MAX-PRIO_MIN)/4) : { return LowPriority; } + case (PRIO_MAX) : { return BackgroundPriority; } + default : return NormalPriority; + } + +} +/***************************************************************************** +** Implementation [Debugging] +*****************************************************************************/ + +std::string print_priority_diagnostics() { + + ostringstream ostream; + + ostream << "\n"; + ostream << "***********************************************************\n"; + ostream << "* System Statistics\n"; + ostream << "***********************************************************\n"; + ostream << "\n"; + + #if _POSIX_PRIORITY_SCHEDULING > 0 + int rr_min = sched_get_priority_min(SCHED_RR); + int rr_max = sched_get_priority_max(SCHED_RR); + if ( ( rr_min == -1 ) || (rr_max == -1) ) { + ecl_throw(StandardException(LOC,NotSupportedError,"The posix SCHED_RR policy is not available on this system [sched_get_priority_min/max].")); + return std::string("The posix SCHED_RR policy is not available on this system [sched_get_priority_min/max]."); + } + ostream << "Real Time Priorities [Low,High]............[" << rr_min << "," << rr_max << "]\n"; + #endif + ostream << "Niceness [Low,High]........................[" << PRIO_MAX << "," << PRIO_MIN << "]\n"; + ostream << "\n"; + ostream << "***********************************************************\n"; + ostream << "* Priority Statistics\n"; + ostream << "***********************************************************\n"; + ostream << "\n"; + #if _POSIX_PRIORITY_SCHEDULING > 0 + int scheduler = sched_getscheduler(0); + switch ( scheduler ) { + case ( -1 ) : { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return std::string("Call to sched_getscheduler failed."); + } + case ( SCHED_OTHER ) : { + ostream << "Scheduler..................................SCHED_OTHER" << "\n"; + break; + } + case ( SCHED_RR ) : { + ostream << "Scheduler..................................SCHED_RR [RT]" << "\n"; + break; + } + case ( SCHED_FIFO ) : { + ostream << "Scheduler..................................SCHED_FIFO [RT]" << "\n"; + break; + } +#if defined(SCHED_BATCH) + case ( SCHED_BATCH ) : { + ostream << "Scheduler..................................SCHED_BATCH" << "\n"; + break; + } +#endif + default : { + ostream << "Scheduler..................................Unknown" << "\n"; + break; + } + } + #endif + switch ( get_priority() ) { + case ( BackgroundPriority ) : { + ostream << "Priority...................................Background\n"; + break; + } + case ( LowPriority ) : { + ostream << "Priority...................................Low\n"; + break; + } + case ( NormalPriority ) : { + ostream << "Priority...................................Normal\n"; + break; + } + case ( HighPriority ) : { + ostream << "Priority...................................High\n"; + break; + } + case ( CriticalPriority ) : { + ostream << "Priority...................................Critical\n"; + break; + } + case ( RealTimePriority4 ) : { + ostream << "Priority...................................RealTime4\n"; + break; + } + case ( RealTimePriority3 ) : { + ostream << "Priority...................................RealTime3\n"; + break; + } + case ( RealTimePriority2 ) : { + ostream << "Priority...................................RealTime2\n"; + break; + } + case ( RealTimePriority1 ) : { + ostream << "Priority...................................RealTime1\n"; + break; + } + case ( DefaultPriority ) : { + ostream << "Priority...................................Default (Inherited)\n"; + break; + } + case ( UnknownPriority ) : { + ostream << "Priority...................................Unknown\n"; + break; + } + } + return ostream.str(); +} + + +/***************************************************************************** +** Hidden Implementations +*****************************************************************************/ + +namespace threads { + +bool set_real_time_priority(int policy, int priority_level) { + + #if _POSIX_PRIORITY_SCHEDULING > 0 + ostringstream ostream; + + /********************* + ** Exception Throwing + **********************/ + if ( priority_level < sched_get_priority_min(policy) ) { + ostream << "The realtime process priority requested was smaller than the minimum value permitted["; + ostream << sched_get_priority_min(policy) << "]\n"; + ecl_throw(StandardException(LOC,OutOfRangeError, ostream.str())); + return false; + } else if (priority_level > sched_get_priority_max(policy) ) { + ostream << "The realtime process priority requested was greater than the maximum value permitted["; + ostream << sched_get_priority_max(policy) << "]\n"; + ecl_throw(StandardException(LOC,OutOfRangeError, ostream.str())); + return false; + } + + /********************* + ** Configuration + **********************/ + sched_param schedule_parameters; + schedule_parameters.sched_priority = priority_level; + if ( sched_setscheduler(0, policy, &schedule_parameters) == -1 ) { + ecl_debug_throw(throwPriorityException(LOC)); + return false; + } + return true; + #else + (void) policy; + (void) priority_level; + ecl_throw(StandardException(LOC,ecl::NotSupportedError,"Your version of posix does not support real time priority scheduling for process management.")); + return false; + #endif +} +} // namespace threads +} // namespace ecl + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_win.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_win.cpp new file mode 100644 index 0000000..8cafdcd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/priority_win.cpp @@ -0,0 +1,202 @@ +/** + * @file /src/lib/priority_win.cpp + * + * @brief Posix priority configuration implementation. + * + * @date April 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/threads/priority_win.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +using std::ostringstream; + +/***************************************************************************** +** Implementation [Process] +*****************************************************************************/ + +bool set_priority(Priority priority_level) +{ + if (priority_level >= RealTimePriority1) { + return threads::set_real_time_priority(0, priority_level); + } + + BOOL bResult = FALSE; + HANDLE hThread = GetCurrentThread(); + + if (!hThread) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return false; + } + + switch (priority_level) { + case CriticalPriority: + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST); + break; + case HighPriority: + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL); + break; + case NormalPriority: + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL); + break; + case LowPriority: + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_BELOW_NORMAL); + break; + case BackgroundPriority: + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_IDLE); + break; + default: + break; + } + + if (!bResult) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return false; + } + + return true; +} + +Priority get_priority() +{ + HANDLE hThread = GetCurrentThread(); + + if (!hThread) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return UnknownPriority; + } + + DWORD dwPriority = GetThreadPriority(hThread); + + switch (dwPriority) { + case THREAD_PRIORITY_TIME_CRITICAL: + return RealTimePriority1; // representative of real-time priority group + case THREAD_PRIORITY_HIGHEST: + return CriticalPriority; + case THREAD_PRIORITY_ABOVE_NORMAL: + return HighPriority; + case THREAD_PRIORITY_NORMAL: + return NormalPriority; + case THREAD_PRIORITY_BELOW_NORMAL: + return LowPriority; + case THREAD_PRIORITY_IDLE: + return BackgroundPriority; + default: + break; + } + + return UnknownPriority; +} + +/***************************************************************************** +** Implementation [Debugging] +*****************************************************************************/ + +std::string print_priority_diagnostics() { + + ostringstream ostream; + + ostream << "\n"; + ostream << "***********************************************************\n"; + ostream << "* Priority Statistics\n"; + ostream << "***********************************************************\n"; + ostream << "\n"; + switch ( get_priority() ) { + case ( BackgroundPriority ) : { + ostream << "Priority...................................Background\n"; + break; + } + case ( LowPriority ) : { + ostream << "Priority...................................Low\n"; + break; + } + case ( NormalPriority ) : { + ostream << "Priority...................................Normal\n"; + break; + } + case ( HighPriority ) : { + ostream << "Priority...................................High\n"; + break; + } + case ( CriticalPriority ) : { + ostream << "Priority...................................Critical\n"; + break; + } + case ( RealTimePriority4 ) : { + ostream << "Priority...................................RealTime4\n"; + break; + } + case ( RealTimePriority3 ) : { + ostream << "Priority...................................RealTime3\n"; + break; + } + case ( RealTimePriority2 ) : { + ostream << "Priority...................................RealTime2\n"; + break; + } + case ( RealTimePriority1 ) : { + ostream << "Priority...................................RealTime1\n"; + break; + } + case ( DefaultPriority ) : { + ostream << "Priority...................................Default (Inherited)\n"; + break; + } + case ( UnknownPriority ) : { + ostream << "Priority...................................Unknown\n"; + break; + } + } + return ostream.str(); +} + + +/***************************************************************************** +** Hidden Implementations +*****************************************************************************/ + +namespace threads { + +bool set_real_time_priority(int policy,int priority_level) { + // policy is ignored + + HANDLE hThread = GetCurrentThread(); + + if (!hThread) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + return false; + } + + BOOL bResult = FALSE; + + if (priority_level >= RealTimePriority1) { + bResult = SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL); + } + + return bResult != FALSE; +} +} // namespace threads +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_pos.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_pos.cpp new file mode 100644 index 0000000..8decbc2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_pos.cpp @@ -0,0 +1,134 @@ +/** + * @file /src/lib/thread_pos.cpp + * + * @brief Posix thread implementation. + * + * @date June 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/threads/thread_pos.hpp" +#include // provides PRIO_MIN, PRIO_MAX for niceness levels + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +* Thread Class Methods +*****************************************************************************/ + +Thread::Thread(VoidFunction function, const Priority &priority, const long &stack_size) : + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, priority, stack_size); +} + +Error Thread::start(VoidFunction function, const Priority &priority, const long &stack_size) +{ + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + initialise(stack_size); + NullaryFreeFunction nullary_function_object = generateFunctionObject(function); + thread_task = new threads::ThreadTask< NullaryFreeFunction >(nullary_function_object, priority); + int result = pthread_create(&(this->thread_handle), &(this->attrs), threads::ThreadTask< NullaryFreeFunction >::EntryPoint, thread_task); + pthread_attr_destroy(&attrs); + if ( result != 0 ) { + delete thread_task; + thread_task = NULL; + ecl_debug_throw(threads::throwPthreadCreateException(LOC,result)); + return threads::handlePthreadCreateError(result); // if in release mode, gracefully fall back to return values. + } + return Error(NoError); +} + +Thread::~Thread() { + // This should work, but it doesn't. pthread_tryjoin_np fails to differentiate + // between an already running thread and one that has already been joined (both + // return EBUSY instead of EBUSY and EINVAL +// int res; +// if ( (res = pthread_tryjoin_np(thread_handle,0)) != 0 ) { +// if ( res == EBUSY ) { +// // still running, so detach. +// pthread_detach(thread_handle); +// } else { +// // Has already been joined, so leave it be. +// } +// } + if ( has_started && !join_requested ) { + pthread_detach(thread_handle); + } +} +void Thread::cancel() { + int result = pthread_cancel(thread_handle); + // Note - if we reach here, then entrypoint hasn't gone through to conclusion and + // subsequently the thread_task object on the heap hasn't been deleted. So... + // always delete it here! + if ( thread_task != NULL ) { + delete thread_task; + thread_task = NULL; + } + if ( result != 0 ) { + ecl_debug_throw(threads::throwPthreadJoinException(LOC,result)); + } +} + +void Thread::join() { + join_requested = true; + if( thread_task != NULL ) { + int result = pthread_join( thread_handle, 0 ); // This also frees up memory like pthread_detach + ecl_assert_throw( result == 0, threads::throwPthreadJoinException(LOC,result)); + (void) result; // for unused variable warnings, in case the assert wasn't triggered + } +} + +void Thread::initialise(const long &stack_size) { + + pthread_attr_init( &attrs ); + /************************************************************************* + ** Linux implementation does not allow PTHREAD_SCOPE_PROCESS + *************************************************************************/ + pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); + // We can't set priorities for SCHED_OTHER (non real time) here anyway, so just use the default + pthread_attr_setinheritsched(&attrs,PTHREAD_INHERIT_SCHED); + + /************************************************************************* + ** Detached State + ************************************************************************** + ** By default on linux, it is joinable. I do cleanup operations within + ** this class, so no need to create it as detached, especially as more + ** often than not, I need to be able to join to the thread again. + *************************************************************************/ + pthread_attr_setdetachstate(&attrs,PTHREAD_CREATE_JOINABLE); + + /************************************************************************* + ** Stack Size + **************************************************************************/ + if ( stack_size != DefaultStackSize ) { + int result = pthread_attr_setstacksize(&attrs,stack_size); + ecl_assert_throw( result == 0, StandardException(LOC,ConfigurationError,"Specified stack size was less than PTHREAD_STACK_MIN or wasn't a multiple of the page size.")); + (void) result; // for unused variable warnings, in case the assert wasn't triggered + } +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_win.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_win.cpp new file mode 100644 index 0000000..006d3fa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/lib/thread_win.cpp @@ -0,0 +1,137 @@ +/** + * @file /src/lib/thread_win.cpp + * + * @brief Win32 thread implementation. + * + * @date April 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/threads/thread_win.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +* Thread Class Methods +*****************************************************************************/ + +Thread::Thread(VoidFunction function, const Priority &priority, const long &stack_size) : + thread_handle(NULL), + thread_task(NULL), + has_started(false), + join_requested(false) +{ + start(function, priority, stack_size); +} + +Error Thread::start(VoidFunction function, const Priority &priority, const long &stack_size) +{ + // stack_size is ignored + + if ( has_started ) { + ecl_debug_throw(StandardException(LOC,BusyError,"The thread has already been started.")); + return Error(BusyError); // if in release mode, gracefully fall back to return values. + } else { + has_started = true; + } + + NullaryFreeFunction nullary_function_object = generateFunctionObject(function); + thread_task = new threads::ThreadTask< NullaryFreeFunction >(nullary_function_object, priority); + + DWORD threadid; + + thread_handle = CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)threads::ThreadTask< NullaryFreeFunction >::EntryPoint, + thread_task, + 0, + &threadid); + + if (!thread_handle) { + ecl_debug_throw(StandardException(LOC, UnknownError, "Failed to create thread.")); + return Error(UnknownError); + } + + BOOL bResult = FALSE; + + if (priority >= RealTimePriority1) { + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL); + } + + switch (priority) { + case CriticalPriority: + bResult = SetThreadPriority(thread_handle, HIGH_PRIORITY_CLASS); + break; + case HighPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_ABOVE_NORMAL); + break; + case LowPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_BELOW_NORMAL); + break; + case BackgroundPriority: + bResult = SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE); + break; + default: + break; + } + + if (!bResult) { + ecl_debug_throw(threads::throwPriorityException(LOC)); + } + + return Error(NoError); +} + +Thread::~Thread() { + cancel(); +} + +void Thread::cancel() { + if (thread_handle) { + unsigned long exitcode; + if (::GetExitCodeThread(thread_handle, &exitcode)) { + if (exitcode == 0x0103) { + // unsafe termination. + ::TerminateThread(thread_handle, exitcode); + } + } + ::CloseHandle(thread_handle); + thread_handle = NULL; + } + if (thread_task) { + delete thread_task; + thread_task = NULL; + } + has_started = false; + join_requested = false; +} + +void Thread::join() { + join_requested = true; + + if (thread_handle) { + WaitForSingleObject(thread_handle, INFINITE); + } +} + +void Thread::initialise(const long &stack_size) { + // stack_size is ignored +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_threads/src/test/CMakeLists.txt new file mode 100644 index 0000000..0205483 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/test/CMakeLists.txt @@ -0,0 +1,44 @@ +############################################################################### +# Test Macro +############################################################################### + +macro(ecl_threads_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries( + ecl_test_${test_name} + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_exceptions::ecl_exceptions + ecl_time::ecl_time + ) + endif() +endmacro() + +############################################################################### +# Special Case +############################################################################### + +# problems running as the jenkins user +set(ECL_JENKINS $ENV{ECL_JENKINS}) +if("${ECL_JENKINS}" STREQUAL "") + ament_add_gtest(ecl_test_mutex mutex.cpp) + if(TARGET ecl_test_mutex) + target_link_libraries( + ecl_test_mutex + ${PROJECT_NAME} + ecl_config::ecl_config + ecl_exceptions::ecl_exceptions + ecl_time::ecl_time + ) + endif() +endif() + +############################################################################### +# Google Tests +############################################################################### + +ecl_threads_add_gtest(priorities) +ecl_threads_add_gtest(threadable) +ecl_threads_add_gtest(threads) diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/test/mutex.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/test/mutex.cpp new file mode 100644 index 0000000..1e39109 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/test/mutex.cpp @@ -0,0 +1,103 @@ +/** + * @file /src/test/mutex.cpp + * + * @brief Unit Test for the @ref ecl::Mutex "Mutex" class. + * + * Use this to test the @ref ecl::Mutex "Mutex" class. Currently this + * only tests the posix mutex class. + * + * @date June 2009 + **/ +/***************************************************************************** + ** Platform Check + *****************************************************************************/ +#include +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/threads/mutex.hpp" + +/***************************************************************************** + ** Using + *****************************************************************************/ + +using ecl::StandardException; +using ecl::Mutex; +using ecl::Duration; + +/***************************************************************************** + ** TESTS + *****************************************************************************/ + +TEST(MutexTests,selfDestruct) +{ + #if defined(NDEBUG) || defined(ECL_NDEBUG) + std::cout << "Skipping deadlock tests - posix doesn't help you in release mode." << std::endl; + SUCCEED(); + #else + // It will now attempt to self-destruct while locked and throw an exception. + // This behaviour is only provided by posix in debug mode. + Mutex mutex; + mutex.lock(); + try { + mutex.lock(); + } catch (StandardException &e) { + SUCCEED(); + } + mutex.unlock(); + #endif +} + +TEST(MutexTests,tryLock) +{ + // It will now attempt to self-destruct while locked and throw an exception. + Mutex mutex; + mutex.trylock(); + EXPECT_FALSE(mutex.trylock()); + mutex.unlock(); +} + +TEST(MutexTests,timedLock) +{ + // It will now attempt to self-destruct while locked and throw an exception. + // Trying to activate from the same thread will cause a deadlock + // and thus exception. Need to make a test with different threads here. + // Duration duration(1,500000000); + // Mutex mutex; + // mutex.lock(); + // mutex.timedlock(duration); +} + +/***************************************************************************** + ** Main program + *****************************************************************************/ + +int main(int argc, char **argv) +{ + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + +#else + +/***************************************************************************** + ** Alternative main + *****************************************************************************/ + +int main(int argc, char **argv) +{ + + std::cout << "Currently not supported on your platform." << std::endl; +} + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/test/priorities.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/test/priorities.cpp new file mode 100644 index 0000000..7f7a93c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/test/priorities.cpp @@ -0,0 +1,102 @@ +/** + * @file /src/test/priorities.cpp + * + * @brief Unit Test for priority configuration. + * + * @date May 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/threads/priority.hpp" +#include + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::set_priority; +using ecl::BackgroundPriority; +using ecl::LowPriority; +using ecl::NormalPriority; +using ecl::HighPriority; +using ecl::CriticalPriority; +using ecl::RealTimePriority4; +using ecl::RealTimePriority3; +using ecl::RealTimePriority2; +using ecl::RealTimePriority1; +using ecl::StandardException; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(PriorityTest,statistics) { + std::string diagnostics = ecl::print_priority_diagnostics(); + SUCCEED(); +} + +TEST(PriorityTest,setPosixPriorities) { + try { + set_priority(BackgroundPriority); + set_priority(LowPriority); + set_priority(NormalPriority); + set_priority(HighPriority); + set_priority(CriticalPriority); + SUCCEED(); + } catch ( const StandardException &e ) { + // often dont have permission to higher level priorities so just warn + // ADD_FAILURE() << "Could not set all the non-real time priorities."; + std::cout << "Do not have permission for the higher level priorities." << std::endl; + } +} + +TEST(PriorityTest,setPosixRealTimePriorities) { + try { + set_priority(RealTimePriority1); + set_priority(RealTimePriority2); + set_priority(RealTimePriority3); + set_priority(RealTimePriority4); + SUCCEED(); + } catch ( const StandardException &e ) { + SUCCEED(); + // often dont have permission for real time scheduling, so just warn + // ADD_FAILURE() << "Could not set all the real time priorities."; + std::cout << "Do not have permission for real time scheduling priorities." << std::endl; + } +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + +#else + +/***************************************************************************** +** Alternative main +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << "Currently not supported on your platform." << std::endl; +} + +#endif /* ECL_IS_POSIX */ + diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/test/threadable.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/test/threadable.cpp new file mode 100644 index 0000000..09009b3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/test/threadable.cpp @@ -0,0 +1,121 @@ +/** + * @file /src/test/threadable.cpp + * + * @brief Unit Test for the @ref ecl::Threadable "Threadable" class. + * + * @date January 2010 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/threads/threadable.hpp" + +/***************************************************************************** +** Doxygen +*****************************************************************************/ +/** + * @cond DO_NOT_DOXYGEN + */ +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::Threadable; + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { +namespace tests { + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class AThreadable : public Threadable { +public: + AThreadable(const unsigned int countdown_start = 5) : top(countdown_start) {} + + void runnable() { + for ( unsigned int i = top; i > 0; --i ) { +// std::cout << "Counting down...." << i << std::endl; + sleep(1); + } + } + +private: + unsigned int top; +}; + +} // namespace tests +} // namespace threads +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::threads::tests::AThreadable; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @endcond + */ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ThreadableTests,runTest) { + AThreadable a; + + a.start(); + while ( a.isRunning() ) { + sleep(1); + } + SUCCEED(); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + +#else + +/***************************************************************************** +** Alternative main +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << "Currently not supported on your platform." << std::endl; +} + +#endif /* ECL_IS_POSIX */ + diff --git a/ros2_ws/src/ecl_core/ecl_threads/src/test/threads.cpp b/ros2_ws/src/ecl_core/ecl_threads/src/test/threads.cpp new file mode 100644 index 0000000..123b37a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_threads/src/test/threads.cpp @@ -0,0 +1,248 @@ +/** + * @file /src/test/threads.cpp + * + * @brief Unit Test for the @ref ecl::Thread "Thread" class. + * + * @date June 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/threads/thread.hpp" + +/***************************************************************************** +** Doxygen +*****************************************************************************/ +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StandardException; +using ecl::Thread; +using ecl::generateFunctionObject; +using ecl::ref; + +/***************************************************************************** +** Globals +*****************************************************************************/ + +// Change this if you want std output. +static const bool output = false; + + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace threads { +namespace tests { + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class ThreadMemberFunctions { +public: + void f() { + if ( output ) { + std::cout << "A::f()" << std::endl; + } + } + void g(const int &i) { + if ( output ) { + std::cout << "A::g(" << i << ")" << std::endl; + } + } +}; + +class NullaryFunction { +public: + NullaryFunction() : i(0) {}; + typedef void result_type; + void operator()() { + for (int j = 0; j < 3; ++j ) { + if ( output ) { + std::cout << " Nullary Function Object: " << i << std::endl; + } + sleep(1); + ++i; + } + if ( output ) { + std::cout << " Nullary Function Object: finished." << std::endl; + } + } + int i; +}; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +void d() { + for (int i = 0; i < 5; ++i ) { + sleep(1); + if ( output ) { + std::cout << " d(): " << i << std::endl; + } + } + if ( output ) { + std::cout << " d(): finished" << std::endl; + } +} +void d_cb() { + if ( output ) { + std::cout << " d(): callback function" << std::endl; + } +} + +void f() { + for (int i = 0; i < 3; ++i) { + if ( output ) { + std::cout << "f(): " << i << std::endl; + } + } +} + +void g(const int &i) { + for (int j = 0; j < 3; ++j) { + if ( output ) { + std::cout << "g(" << i << ")" << std::endl; + } + } +} + +void deconstructThread() { + Thread thread_deconstruct(d); +} + +} // namespace Tests +} // namespace threads +} // namespace ecl + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::threads::tests; + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @endcond + */ + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ThreadTests,threadFunctionTypes) { + ThreadMemberFunctions a; + Thread thread_f1(f); + Thread thread_f2(&ThreadMemberFunctions::f,a); + Thread thread_f3(generateFunctionObject(f)); + Thread thread_f4(generateFunctionObject(g,1)); + Thread thread_f5(generateFunctionObject(&ThreadMemberFunctions::f,a)); + Thread thread_f6(generateFunctionObject(&ThreadMemberFunctions::g,a,2)); + thread_f1.join(); + thread_f2.join(); + thread_f3.join(); + thread_f4.join(); + thread_f5.join(); + thread_f6.join(); + SUCCEED(); +} + +TEST(ThreadTests,cancelThread) { + Thread thread(generateFunctionObject(d)); + sleep(3); + EXPECT_TRUE(thread.isRunning()); +// std::cout << "Cancelling d() thread (you should see no further output)." << std::endl; + thread.cancel(); + EXPECT_FALSE(thread.isRunning()); + thread.join(); + EXPECT_FALSE(thread.isRunning()); +} + +TEST(ThreadTests,deconstruct) { + deconstructThread(); + sleep(6); + SUCCEED(); +} + +TEST(ThreadTests,nullaryFunctionObjects) { + NullaryFunction function_object; + Thread thread_f8(function_object); // Thread thread_f8 = NullaryFunction(); + sleep(4); + Thread thread_f9(ref(function_object)); + sleep(4); + thread_f8.join(); + thread_f9.join(); + SUCCEED(); +} + +TEST(ThreadTests,stackSize) { + Thread thread(f,ecl::DefaultPriority,1024*1024); + thread.join(); + SUCCEED(); +} + +TEST(ThreadTests,delayedStart) { + + NullaryFunction function_object; + ThreadMemberFunctions a; + Thread thread1, thread2, thread3, thread4; + thread1.start(f); + thread2.start(function_object); + thread3.start(&ThreadMemberFunctions::f,a); + thread4.start(generateFunctionObject(&ThreadMemberFunctions::g,a,2)); + thread1.join(); + thread2.join(); + thread3.join(); + thread4.join(); + SUCCEED(); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +#else + +/***************************************************************************** +** Alternative main +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << "Currently not supported on your platform." << std::endl; +} + +#endif /* ECL_IS_POSIX */ + diff --git a/ros2_ws/src/ecl_core/ecl_time/.cproject b/ros2_ws/src/ecl_core/ecl_time/.cproject new file mode 100644 index 0000000..049b8c9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/.cproject @@ -0,0 +1,260 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + all + true + true + true + + + make + clean + true + true + true + + + make + test + true + true + true + + + make + tests + true + true + true + + + make + + examples + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_time/.project b/ros2_ws/src/ecl_core/ecl_time/.project new file mode 100644 index 0000000..6aa07d5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/.project @@ -0,0 +1,78 @@ + + + ecl_time + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_time/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_time/CHANGELOG.rst new file mode 100644 index 0000000..aab5a63 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/CHANGELOG.rst @@ -0,0 +1,29 @@ +========= +Changelog +========= + +0.61.17 (2017-02-05) +-------------------- +* bugfix realtime_now() to not return temporaries + +0.61.12 (2016-05-03) +-------------------- +* consideration for time on apple for the frequency class + +0.61.6 (2015-11-25) +------------------- +* bugfix frequency monitor timestamp initialisation + +0.61.5 (2015-11-24) +------------------- +* frequency monitor + +0.61.1 (2015-07-22) +------------------- +* negative support for timestamps + +0.61.0 (2014-09-12) +------------------- +* random number generator +* optional realtime stamping (not monotone) to sync with ros stamps + diff --git a/ros2_ws/src/ecl_core/ecl_time/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/CMakeLists.txt new file mode 100644 index 0000000..4350414 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/CMakeLists.txt @@ -0,0 +1,54 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_time) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) +find_package(ecl_exceptions REQUIRED) +find_package(ecl_time_lite REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors + ecl_exceptions + ecl_time_lite +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_time/doxygen/changelog.dox b/ros2_ws/src/ecl_core/ecl_time/doxygen/changelog.dox new file mode 100644 index 0000000..dec3356 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/doxygen/changelog.dox @@ -0,0 +1,15 @@ +/** + @page changelog ChangeLog + + @section Changes + + - Apr 11 : Updated for better exception handling, low level functionality moved to ecl_time_lite. + - Sep 10 : CpuWatch for systems with rt timers. + - May 10 : Timestamp win32 implementation. + - May 10 : Cmake win32 framework. + - Feb 10 : Improved the @ref ecl::Sleep "sleep" interface to allow for preconfigured sleeps (faster). + - Dec 09 : Provide absolute timing on periodic loops with the @ref ecl::Snooze "Snooze" class. + - May 09 : Emulate @ref ecl::StopWatch "stopwatch" functionalities (start, stop, elapsed, split). + - May 09 : Records system time/express the concept of durations with @ref ecl::TimeStamp "timestamps". + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_time/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_time/doxygen/mainpage.dox new file mode 100644 index 0000000..f4c16f4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/doxygen/mainpage.dox @@ -0,0 +1,234 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Timing utilities are very dependent on the system api provided for their use. + This package provides a means for handling different timing models. + +@subsection posixRtTimers Posix RT Timers + + Posix timers record times as a pair : (seconds,nanoseconds), so they have a + very fine resolution, but it needs to remembered that the system latency + will still affect their results. For example, sleeping for 1nanosecond + wont work as you expect, since the system latency will usually mean the + command has to wait for the scheduler to grant it a slice of the action + (usually a wait of around 1ms on a linux desktop). This latency is usually + configured by the scheduler being used by the kernel. + + Returning to the pair, the first unit, seconds is usually of a system defined + type. This allows it to be extendable to a larger type in the future if + the system time requires a larger value. The latter is measured with the + long variable, which is more than sufficient to cater for 1x10^9 units. + +@subsection macOSTimers MacOSX Timers + + MacOSX timers are mostly posix, however they are missing the extensions + provided by the librt library, e.g. clock_gettime and clock_nanosleep. The + real downside of this is that it is not possible to use absolute time with + the macosx posix timers (i.e. periodic timers will drift). + + There are another set of mac specific timers that will let you do this, but + it has not yet been implemented. + +@subsection windozeTimers Windows Timers + + I haven't yet implemented these. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that uses + time functions or classes. + @code + #include + + // The time classes + using ecl::CpuWatch; + using ecl::Duration; + using ecl::MicroSleep; + using ecl::MilliSleep; + using ecl::NanoSleep; + using ecl::Sleep; + using ecl::Snooze; + using ecl::StopWatch; + using ecl::TimeData; + using ecl::TimeStamp; + @endcode + + You will also need to link to -lecl_time. + +\section usage Usage + + @subsection Timestamps + + Timestamps provide a means of doing one of two things: + + - Recording the system time since some reference point. + - Manually recording a timestamp, or time duration (e.g. result of a timestamp difference operation). + + There are several ways of initialising the timestamp: + @code + TimeStamp time_system; // Automatically captures system time since Epoch. + TimeStamp time_double(3.21) // Initialise with a decimalised time (slow). + TimeStamp time_pair(3,210000000) // Initialise with a (s,ns) pair (fast for posix rt systems). + @endcode + + These operations can also be performed to set the timestamp after construction: + + @code + time_system.stamp(); // Automatically captures system time since Epoch. + time_double.stamp(3.21) // Initialise with a decimalised time (slow). + time_pair.stamp(3,210000000) // Initialise with a (s,ns) pair (fast for posix rt systems). + @endcode + + All the usual comparison (==,!=,<=,>=,<,>) and mathematical (+,-,+=,-=) operations can also be used. + + @code + if ( time_system > time_double ) { + time_system -= time_double; + } + @endcode + + Streaming: + + @code + TimeStamp timestamp; // captures current time + std::cout << timestamp << std::endl; // 1682346.235653090 + @endcode + + Caution: The only thing to be wary of with timestamps is to remember that they + must always be positive. This was a design decision that keeps the timestamp class as light as + possible. If negativity was introduced, an extra sign bit would be required, and in almost all + timestamp operations, this is not necessary. + + Exceptions: The timestamp class will throw exceptions (in debug mode only) whenever a + timestamp method is used that would create a negative timestamp. + + @subsection Duration + + Durations are intended to intuitively represent the passage of time. Although is is conceptually + different from a timestamp, the functionality under the hood is currently identical. Subsequently, + the @ref ecl::TimeStamp "Timestamp" class is currently typedef'd to the @ref ecl::Duration + "Duration" class. + + This might change at some point in the future if we require negativity (as mentioned above). + + @subsection StopWatch + + This is a fairly intuitive class and uses the TimeStamp class under the hood for recording + times. + + Note that the stopwatch starts automatically, just use restart() if you + wish to reset and start again. + + @code + StopWatch stopwatch; + TimeStamp time; + time = stopwatch.split() + cout << time << endl; + time = stopwatch.elapsed() + cout << time << endl; + stopwatch.restart(); + @endcode + + @subsection CpuWatch + + This is a variation of the stopwatch for systems with librt. The time measured by the + cpu watch is not system time, rather the time spent by the process actually exeucting + on the cpu. This is very useful for benchmarking programs. Usage is exactly the same as for + the stopwatch. + + @subsection Sleep + + Some simple sleep classes. They can be used directly or preconfigured. + + @code + Duration duration(1,300000000); + Sleep sleep; + MilliSleep sleep_ms; + MicroSleep sleep_us; + NanoSleep sleep_ns; + + // Direct sleep commands + sleep(duration); + sleep(3); + sleep_ms(3500); + sleep_us(500000); + sleep_ns(500000000); + + // Preconfigured (i.e. use last configured command) + MilliSleep pc_sleep_ms(duration); + sleep_ms(); // uses the last configuration + pc_sleep_ms(); // uses the constructor configuration + @endcode + + @subsection Snooze + + Snooze is a periodic sleeper, useful in control loops where you want to exactly control the + time taken by each loop. Using a regular sleep function to do this can cause some time + drift problems (refer to the snooze class documentation for more detail). The snooze + class gets around this by setting its periodic timestamps off the absolute clock time + rather than calculating relative time splits. + + @code + Snooze snooze(Duration(0,20000000); // 20ms snooze + // Some preliminaries + snooze.initialise(); // make sure the snoozer is sync'ed with the current time. + while (1) { + // do some work + snooze(); + } + @endcode + + Note, this can be problematic if the periodic timestamps get behind the current time. To + remedy this, by default the class validates the timestamp at each check and syncs it with + the current time if it starts to lag behind (can easily be caused by the system scheduler + knocking it out of whack in favour of another process). This can be manually turned + off in the constructor if you're confident of the timing processes and this will marginally + reduce the snoozer's latency. + + @subsection TimeData + + This is a benchmarking utility for storing timings and then analysing them with some statistical + methods. + + @code + CpuWatch cpuwatch; + TimeData timings; + ecl::Duration duration; + for ( unsigned int i = 0; i < 100; ++i ) { + cpuwatch.restart(); + // do some work here + duration = cpuwatch.split(); + timings.push_back(duration); + } + std::cout << "Average : " << timings.average() << std::endl; + std::cout << "Variance: " << timings.variance() << std::endl; + @endcode + +\section unitTests Unit Tests + + - src/test/cpuwatch_rt.cpp + - src/test/sleep.cpp + - src/test/snooze.cpp + - src/test/stopwatch.cpp + - src/test/timestamp.cpp + - src/test/time_data.cpp + +\section Examples + + - src/examples/sleep.cpp + +\section utilities Utilities + + - /ecl_core_apps/src/benchmarks/snooze.cpp : benchmarks the latencies for the periodic timer. + +\section ChangeLog + + - @ref changelog "ChangeLog" + +@section Errata + + The cross-platform support, particularly the macosx absolute timers really needs to be done. +*/ diff --git a/ros2_ws/src/ecl_core/ecl_time/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_time/doxygen/namespaces.dox new file mode 100644 index 0000000..1ed6d0c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/doxygen/namespaces.dox @@ -0,0 +1,15 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ +/** + * @namespace ecl::time + * + * @brief Supporting elements and interfaces. + * + * These provide support for the elements in this package. They are not + * intended to be directly visible to the user. + **/ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..0948458 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(time) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time.hpp new file mode 100644 index 0000000..0b8e528 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time.hpp @@ -0,0 +1,42 @@ +/** + * @file /include/ecl/time.hpp + * + * @brief Various classes for timing activities. + * + * @date May, 2009. + **/ + +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_HPP_ +#define ECL_TIME_HPP_ + + +/***************************************************************************** +** Includes +*****************************************************************************/ +#include + + +#ifdef emit + #undef emit + #define replace_qt_emit +#endif + +#include "time/duration.hpp" +#include +#include "time/random_number_generator.hpp" +#include "time/sleep.hpp" // Posix rt-timers only +#include "time/snooze.hpp" // Posix rt-timers only +#include "time/stopwatch.hpp" // Posix rt-timers only +#include "time/time_data.hpp" +#include "time/timestamp.hpp" + +#ifdef replace_qt_emit + #define emit +#endif + + +#endif /*ECL_TIME_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/CMakeLists.txt new file mode 100644 index 0000000..028bbee --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/time) + diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch.hpp new file mode 100644 index 0000000..3f1a483 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch.hpp @@ -0,0 +1,32 @@ +/** + * @file /ecl_time/include/ecl/time/cpuwatch.hpp + * + * @brief Platform switcher for the cpu watch interface. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_CPUWATCH_HPP_ +#define ECL_TIME_CPUWATCH_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +// Currently the cpuwatch timers are only defined for rt timers, so +// the cpuwatch class is similarly defined. +#if defined(ECL_IS_POSIX) + // monotonic clock, cpu clock -> clock_gettime; clock_selection -> clock_nanosleep + #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK) >= 0L && defined(_POSIX_CLOCK_SELECTION) && (_POSIX_CLOCK_SELECTION) >= 0L + #include "cpuwatch_rt.hpp" + #else + // No fallback available + #endif +#endif + +#endif /* ECL_TIME_CPUWATCH_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch_rt.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch_rt.hpp new file mode 100644 index 0000000..57d798b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/cpuwatch_rt.hpp @@ -0,0 +1,114 @@ +/** + * @file /ecl_time/include/ecl/time/cpuwatch_rt.hpp + * + * @brief This class measures cpu time for a process. + * + * Currently it is only valid for systems with rt timers, i.e. clock_gettime. + * This is constrained by the selection made in cpuwatch.hpp. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_CPUWATCH_POS_HPP_ +#define ECL_TIME_CPUWATCH_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#if defined(ECL_IS_POSIX) + // monotonic clock, cpu clock -> clock_gettime; clock_selection -> clock_nanosleep + #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK) >= 0L && defined(_POSIX_CLOCK_SELECTION) && (_POSIX_CLOCK_SELECTION) >= 0L + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "timestamp.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @brief A stopwatch that runs on a process's cpu time. + * + * This measures the time spent by the process executing on the cpu itself. + * A good stopwatch for benchmarking tests. + * + * Functionally, it uses the TimeStamp class as a means of recording time, + * splits and elapsed time. Its operation should be intuitive. + * + * This is only valid on platforms with a supporting timestamp + * implementation and rt timers (needs clock_gettime with + * CLOCK_PROCESS_CPUTIME_ID. + * + * Note that the cpuwatch starts automatically, just use restart() if you + * wish to reset and start again. + * + * Usage: + * @code + * CpuWatch cpuwatch; + * TimeStamp time; + * time = cpuwatch.split() + * cout << time << endl; + * time = cpuwatch.elapsed() + * cout << time << endl; + * cpuwatch.restart(); + * @endcode + **/ +class ecl_time_PUBLIC CpuWatch +{ + public: + /** + * Default constructor that initialises the cpuwatch with the current + * system time to use as a point of reference. + **/ + CpuWatch(); + + virtual ~CpuWatch() {} + /** + * @brief Restarts the cpuwatch. + * + * Restarts the cpuwatch (i.e. re-initialises the cpuwatch with the + * current system time as its point of reference). + **/ + void restart(); + + /** + * @brief Calculates the total elapsed time. + * + * Calculates the total elapsed time since the cpuwatch was started. + * @return TimeStamp : the total elapsed time since (re)started. + **/ + TimeStamp elapsed(); + /** + * @brief Calculates the current split. + * + * Calculates the elapsed time since the last split. + * @return TimeStamp : the elapsed time since the last split. + **/ + TimeStamp split(); + + private: + TimeStamp start_time, split_time; + timespec tmp; // use for temporary cacluations. +}; + +} // namespace ecl + +#endif /* MANY POSIX TIME REQ'MENTS */ +#endif /* ECL_IS_POSIX */ +#endif /* ECL_TIME_CPUWATCH_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/duration.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/duration.hpp new file mode 100644 index 0000000..0407b19 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/duration.hpp @@ -0,0 +1,45 @@ +/** + * @file /include/ecl/time/duration.hpp + * + * @brief Cross-platform header inclusions for the duration typedefs. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_DURATION_HPP_ +#define ECL_TIME_DURATION_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #include "timestamp_pos.hpp" +#elif defined(ECL_IS_WIN32) + #include "timestamp_win.hpp" +#endif + +namespace ecl { + + /** + * @brief Convenience typedef to associate timestamps with the concept of durations. + * + * Both timestamps and durations utilise similar functionality under the hood, + * even though they are conceptually different. The only thing I might consider + * if creating a separate class for durations is to introduce negativity. + * However, I've yet to find a real use for it. + */ + typedef TimeStamp Duration; + +} // namespace ecl + +#endif /* ECL_TIME_DURATION_HPP */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/frequency.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/frequency.hpp new file mode 100644 index 0000000..458ed69 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/frequency.hpp @@ -0,0 +1,132 @@ +/** + * @file /ecl_time/include/ecl/time/frequency_diagnostics.hpp + */ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ecl_time_TIME_FREQUENCY_DIAGNOSTICS_HPP_ +#define ecl_time_TIME_FREQUENCY_DIAGNOSTICS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "timestamp.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interfaces +*****************************************************************************/ +/** + * @brief Data relevant to frequencies of an incoming stream. + * + * Typical use case is for characterising an incoming stream of sensor data. + */ +struct FrequencyDiagnostics { + + FrequencyDiagnostics() + : has_connection(false) + , hz(-1.0) + , std_dev(-1.0) + , minimum_interval(-1.0) + , maximum_interval(-1.0) + , last_incoming() + {} + + bool has_connection; + float hz; + float std_dev; + float minimum_interval; + float maximum_interval; + float last_incoming; + +}; + +/** + * @brief Lightweight and fast frequency monitor. + * + * This class doesn't dynamically update over a window, nor does it collect + * and store data to compute characteristics like standard deviations. It is + * however, suitable for most use case scenarios where you are simply + * interested in the hz/minimum_interval/maximum_interval of data over + * a fixed period. + * + * Usage: + * + * + * @code + * float window_period = 2.0; + * FrequencyMonitor monitor(window_period, false); + * FrequencyMonitor ros_monitor(window_period, true); // use the realtime clock to match ros timestamps + * FrequencyDiagnostics diagnostics; + * + * void incomingDataCallback() { + * monitor.update(); // register that new data has arrived + * } + * + * void process() { + * diagnostics = monitor.analyse(); + * } + * + * void process2() { + * monitor.analyse(); + * diagnostics = monitor.getDiagnostics(); + * } + * @endcode + */ +class FrequencyMonitor { +public: + /** + * @brief Setup the frequency monitor. + * + * @param window_period : time interval over which updates are analysed. + * @param use_realtime_clock : better to use the monotonic clock, but sometimes (e.g. ros), realtime is required. + */ + FrequencyMonitor( + const float& window_period = 2.0, + const bool& use_realtime_clock=false + ); + /** + * @brief Let the diagnostics know that new data has arrived. + * + * This updates the internal counter, with a timestamp. + */ + void update(); + /** + * @brief Analyse the recent updates to generate monitoring statistics. + * + * Right now this just uses a fixed window (not moving) that only updates the information if + * the period since the last analyse() request was made has been exceeded. + */ + const FrequencyDiagnostics& analyse(); + + /** + * @brief Diagnostics getter function. + * @return FrequencyDiagnostics + */ + const FrequencyDiagnostics& diagnostics() const { return current_diagnostics; }; + +protected: + FrequencyDiagnostics current_diagnostics; + unsigned int incoming_counter; + ecl::TimeStamp last_anyalsed; + ecl::TimeStamp minimum_interval; + ecl::TimeStamp maximum_interval; + ecl::TimeStamp period; + bool use_realtime_clock; + ecl::TimeStamp last_incoming; +}; + +/***************************************************************************** +** Trailers +*****************************************************************************/ + +} // namespace ecl + +#endif /* ecl_time_TIME_FREQUENCY_DIAGNOSTICS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/macros.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/macros.hpp new file mode 100644 index 0000000..67db40d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/macros.hpp @@ -0,0 +1,41 @@ +/** + * @file /include/ecl/time/macros.hpp + * + * @brief Macros for ecl time. + * + * @date April, 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_MACROS_HPP_ +#define ECL_TIME_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Declspecs +*****************************************************************************/ + +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_time_EXPORTS // we are building a shared lib/dll + #define ecl_time_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_time_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_time_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_time_PUBLIC + #define ecl_time_LOCAL +#endif + +#endif /* ECL_TIME_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/random_number_generator.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/random_number_generator.hpp new file mode 100644 index 0000000..37c2ed4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/random_number_generator.hpp @@ -0,0 +1,135 @@ +/** + * @file /include/ecl/time/random_number_generator.hpp + * + * @brief Seeding and generating various random number generator distributions. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_RANDOM_NUMBER_GENERATOR_HPP_ +#define ECL_TIME_RANDOM_NUMBER_GENERATOR_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Random Number Generator +*****************************************************************************/ +/** + * @brief A random number generator + */ +template +class RandomNumberGenerator +{ +public: + RandomNumberGenerator( const unsigned int randSeed ) + { + srand( randSeed ); + } + + RandomNumberGenerator() + { + RandomNumberGenerator::seed(); + } + + T uniform( const T & range) + { + return (uniform()-0.5)*2.0*range; + } + + T uniform() + { + return static_cast(rand())/static_cast(RAND_MAX); + } + + T gaussian( const T & std, const T & mu = 0 ) + { + T x1, x2, w, y1; + static T y2; + static bool use_last = false; + + if (use_last) /* use value from previous call */ + { + y1 = y2; + use_last = false; + } + else + { + do { + x1 = 2.0 * uniform() - 1.0; + x2 = 2.0 * uniform() - 1.0; + w = x1 * x1 + x2 * x2; + } while ( w >= 1.0 ); + + w = std::sqrt( (-2.0 * std::log( w ) ) / w ); + y1 = x1 * w; + y2 = x2 * w; + use_last = true; + } + + return mu + y1 * std; + } + +private: + /** + * @brief Seed the system random number generator. + * + * Here we create a seed by hashing from three independent sources. + * This is a more robust way to get a reliable seed that allows + * you to get the typically para-optimal traits + * + * 1) fine grained (e.g. you want to call srand two times in a *very* short interval) + * 2) low chance of collisions over a long period + * + * It also avoids having to use esoteric linux functions lick clock_gettime that + * aren't available on all platforms. + * + * References: + * + * -h ttp://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand + * - http://burtleburtle.net/bob/hash/doobs.html + */ + static void seed() + { + unsigned long a = clock(); + unsigned long b = ::time(NULL); + +#if defined(ECL_IS_WIN32) + unsigned long c = GetCurrentProcessId(); +#else + unsigned long c = getpid(); +#endif + + a=a-b; a=a-c; a=a^(c >> 13); + b=b-c; b=b-a; b=b^(a << 8); + c=c-a; c=c-b; c=c^(b >> 13); + a=a-b; a=a-c; a=a^(c >> 12); + b=b-c; b=b-a; b=b^(a << 16); + c=c-a; c=c-b; c=c^(b >> 5); + a=a-b; a=a-c; a=a^(c >> 3); + b=b-c; b=b-a; b=b^(a << 10); + c=c-a; c=c-b; c=c^(b >> 15); + srand(c); + } +}; + +} // namespace ecl + + +#endif /* ECL_TIME_RANDOM_NUMBER_GENERATOR_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep.hpp new file mode 100644 index 0000000..66272b3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep.hpp @@ -0,0 +1,31 @@ +/** + * @file /include/ecl/time/sleep.hpp + * + * @brief Cross-platform header inclusions for the sleep class. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SLEEP_HPP_ +#define ECL_TIME_SLEEP_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #include "sleep_pos.hpp" +#elif defined(ECL_IS_WIN32) + #include "sleep_win.hpp" +#endif + +#endif /* ECL_TIME_SLEEP_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_pos.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_pos.hpp new file mode 100644 index 0000000..03b8423 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_pos.hpp @@ -0,0 +1,353 @@ +/** + * @file /include/ecl/time/sleep_pos.hpp + * + * @brief Interface for the sleep classes utilising posix timers. + * + * @date August 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SLEEP_POS_HPP_ +#define ECL_TIME_SLEEP_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "duration.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Sleep] +*****************************************************************************/ +/** + * @brief General purpose sleeper. + * + * General purpose sleeper. This works with the Duration structure which + * allows time setting of any resolution. Alternatively, a simple + * 'seconds' resolution operator is available for convenience. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, MilliSleep, MicroSleep, NanoSleep. + */ +class ecl_time_PUBLIC Sleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified duration. + * + * Preconfigures the sleep functor with a specified duration. Note that the + * preconfigured value may be changed later via operator()(const Duration &duration) + * or operator()(const unsigned long &seconds). + * + * @param duration : preconfigured duration. + */ + Sleep(const Duration &duration); + /** + * @brief Preconfigures the sleep functor with a specified length (in secs). + * + * Preconfigures the sleep functor with a specified length (secs). Note that the + * preconfigured value may be changed later via operator()(const Duration &duration) + * or operator()(const unsigned long &seconds). + * + * @param seconds : preconfigured sleep time (secs). + */ + Sleep(const unsigned long &seconds = 0); + virtual ~Sleep() {} + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + + /** + * @brief Sleeper functor method for seconds resolution sleeps. + * + * Sleeper functor method for seconds resolution sleeps. + * + * @param seconds : number of seconds to sleep for. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &seconds); + /** + * @brief Sleeper functor method for sleeping at any resolution. + * + * Sleeper functor method for sleeping at any resolution. + * + * @param duration : the sleep duration. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const Duration &duration); + +private: + timespec required, remaining; +}; + +/** + * @brief Milliseconds resolution sleeper. + * + * This sleeper works on the milliseconds range, [0-1000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MicroSleep, NanoSleep. + */ +class ecl_time_PUBLIC MilliSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (msecs). + * + * Preconfigures the sleep functor with a specified length (msecs). Note that the + * preconfigured value may be changed later via + * operator()(const unsigned long &milliseconds). + * + * @param milliseconds : preconfigured sleep time (msecs). + */ + MilliSleep(const unsigned long &milliseconds = 0); + + virtual ~MilliSleep() {} + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + + /** + * @brief Sleeper functor method for milliseconds resolution sleeps. + * + * Sleeper functor method for milliseconds resolution sleeps. + * + * @param milliseconds : number of milli_seconds to sleep for [0-1000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &milliseconds); +private: + timespec required, remaining; +}; + +/** + * @brief Microseconds resolution sleeper. + * + * This sleeper works on the microseconds range, [0-1000000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MilliSleep, NanoSleep. + */ +class ecl_time_PUBLIC MicroSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (usecs). + * + * Preconfigures the sleep functor with a specified length (usecs). + * Note that the preconfigured value may be changed later via + * operator()(const unsigned long µseconds). + * + * @param microseconds : preconfigured sleep time (usecs). + */ + MicroSleep(const unsigned long µseconds = 0); + + virtual ~MicroSleep() {} + + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + /** + * @brief Sleeper functor method for microseconds resolution sleeps. + * + * Sleeper functor method for microseconds resolution sleeps. + * + * @param micro_seconds : number of micro_seconds to sleep for [0-1000000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long µ_seconds); +private: + timespec required, remaining; +}; + +/** + * @brief Nanoseconds resolution sleeper. + * + * This sleeper works on the nanoseconds range, [0-1000000000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MilliSleep, MicroSleep. + */ +class ecl_time_PUBLIC NanoSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (nsecs). + * + * Preconfigures the sleep functor with a specified length (nsecs). + * Note that the preconfigured value may be changed later via + * operator()(const unsigned long &nanoseconds). + * + * @param nanoseconds : preconfigured sleep time (nsecs). + */ + NanoSleep(const unsigned long &nanoseconds = 0); + + virtual ~NanoSleep() {} + + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + /** + * @brief Sleeper functor method for nanoseconds resolution sleeps. + * + * Sleeper functor method for nanoseconds resolution sleeps. + * + * @param nanoseconds : number of nano_seconds to sleep for [0-1000000000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &nanoseconds); +private: + timespec required, remaining; +}; + + +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions][Sleeper Classes] +*****************************************************************************/ + +#if defined(ECL_HAS_EXCEPTIONS) +namespace ecl { +namespace time { + + +/***************************************************************************** +** Interface [Sleep Exceptions] +*****************************************************************************/ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by usleep and nanosleep posix + * functions used in the sleeper classes. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +inline ecl::StandardException throwSleepException(const char* loc ) { + int error_result = errno; + switch (error_result) { + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, "A posix signal interrupted the sleep."); + case ( EINVAL ) : return StandardException(loc, ecl::InvalidInputError, "Specified value was negative or exceeded resolution range.\n\n Sleep: [N/A]\n MilliSleep: [0-1000]\n MicroSleep: [0-1x10^6]\n NanoSleep: [0-1x10^9]\n"); + case ( EFAULT ) : return StandardException(loc, ecl::MemoryError, "Internal posix issue copying information from user space."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } + +} + + +} // namespace time +} // namespace ecl +#endif + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_TIME_SLEEP_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_win.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_win.hpp new file mode 100644 index 0000000..15f46fb --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/sleep_win.hpp @@ -0,0 +1,354 @@ +/** + * @file /include/ecl/time/sleep_win.hpp + * + * @brief Interface for the sleep classes utilising posix timers. + * + * @date April 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SLEEP_WIN_HPP_ +#define ECL_TIME_SLEEP_WIN_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "duration.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Sleep] +*****************************************************************************/ +/** + * @brief General purpose sleeper. + * + * General purpose sleeper. This works with the Duration structure which + * allows time setting of any resolution. Alternatively, a simple + * 'seconds' resolution operator is available for convenience. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, MilliSleep, MicroSleep, NanoSleep. + */ +class ecl_time_PUBLIC Sleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified duration. + * + * Preconfigures the sleep functor with a specified duration. Note that the + * preconfigured value may be changed later via operator()(const Duration &duration) + * or operator()(const unsigned long &seconds). + * + * @param duration : preconfigured duration. + */ + Sleep(const Duration &duration); + /** + * @brief Preconfigures the sleep functor with a specified length (in secs). + * + * Preconfigures the sleep functor with a specified length (secs). Note that the + * preconfigured value may be changed later via operator()(const Duration &duration) + * or operator()(const unsigned long &seconds). + * + * @param seconds : preconfigured sleep time (secs). + */ + Sleep(const unsigned long &seconds = 0); + virtual ~Sleep() {} + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + + /** + * @brief Sleeper functor method for seconds resolution sleeps. + * + * Sleeper functor method for seconds resolution sleeps. + * + * @param seconds : number of seconds to sleep for. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &seconds); + /** + * @brief Sleeper functor method for sleeping at any resolution. + * + * Sleeper functor method for sleeping at any resolution. + * + * @param duration : the sleep duration. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const Duration &duration); + +private: + TimeStructure required, remaining; +}; + +/** + * @brief Milliseconds resolution sleeper. + * + * This sleeper works on the milliseconds range, [0-1000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MicroSleep, NanoSleep. + */ +class ecl_time_PUBLIC MilliSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (msecs). + * + * Preconfigures the sleep functor with a specified length (msecs). Note that the + * preconfigured value may be changed later via + * operator()(const unsigned long &milliseconds). + * + * @param milliseconds : preconfigured sleep time (msecs). + */ + MilliSleep(const unsigned long &milliseconds = 0); + + virtual ~MilliSleep() {} + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + + /** + * @brief Sleeper functor method for milliseconds resolution sleeps. + * + * Sleeper functor method for milliseconds resolution sleeps. + * + * @param milliseconds : number of milli_seconds to sleep for [0-1000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &milliseconds); +private: + TimeStructure required, remaining; +}; + +/** + * @brief Microseconds resolution sleeper. + * + * This sleeper works on the microseconds range, [0-1000000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MilliSleep, NanoSleep. + */ +class ecl_time_PUBLIC MicroSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (usecs). + * + * Preconfigures the sleep functor with a specified length (usecs). + * Note that the preconfigured value may be changed later via + * operator()(const unsigned long µseconds). + * + * @param microseconds : preconfigured sleep time (usecs). + */ + MicroSleep(const unsigned long µseconds = 0); + + virtual ~MicroSleep() {} + + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + /** + * @brief Sleeper functor method for microseconds resolution sleeps. + * + * Sleeper functor method for microseconds resolution sleeps. + * + * @param micro_seconds : number of micro_seconds to sleep for [0-1000000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long µ_seconds); +private: + TimeStructure required, remaining; +}; + +/** + * @brief Nanoseconds resolution sleeper. + * + * This sleeper works on the nanoseconds range, [0-1000000000]. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit (more likely). + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + * + * @sa Duration, Sleep, MilliSleep, MicroSleep. + */ +class ecl_time_PUBLIC NanoSleep { +public: + /** + * @brief Preconfigures the sleep functor with a specified length (nsecs). + * + * Preconfigures the sleep functor with a specified length (nsecs). + * Note that the preconfigured value may be changed later via + * operator()(const unsigned long &nanoseconds). + * + * @param nanoseconds : preconfigured sleep time (nsecs). + */ + NanoSleep(const unsigned long &nanoseconds = 0); + + virtual ~NanoSleep() {} + + + /** + * @brief Executes the sleeper for the currently configured sleep time. + * + * Uses the last configured sleep time for the sleeper and executes. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(); + /** + * @brief Returns the currently configured sleep time for this sleeper. + * + * Returns the currently configured sleep time for this sleeper. + * + * @return Duration : the current sleep time. + */ + Duration duration() { return Duration(required.tv_sec,required.tv_nsec); } + /** + * @brief Sleeper functor method for nanoseconds resolution sleeps. + * + * Sleeper functor method for nanoseconds resolution sleeps. + * + * @param nanoseconds : number of nano_seconds to sleep for [0-1000000000]. + * + * @exception StandardException : throws if the sleep function fails [debug mode only]. + */ + void operator()(const unsigned long &nanoseconds); +private: + TimeStructure required, remaining; +}; + + +} // namespace ecl + +/***************************************************************************** +** Interface [Exceptions][Sleeper Classes] +*****************************************************************************/ + +#if defined(ECL_HAS_EXCEPTIONS) +namespace ecl { +namespace time { + + +/***************************************************************************** +** Interface [Sleep Exceptions] +*****************************************************************************/ +/** + * This function generates a custom StandardException response + * for posix error numbers generated by usleep and nanosleep posix + * functions used in the sleeper classes. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +inline ecl::StandardException throwSleepException(const char* loc ) { + int error_result = errno; + switch (error_result) { + case ( EINTR ) : return StandardException(loc, ecl::InterruptedError, "Interrupted the sleep."); + case ( EINVAL ) : return StandardException(loc, ecl::InvalidInputError, "Specified value was negative or exceeded resolution range.\n\n Sleep: [N/A]\n MilliSleep: [0-1000]\n MicroSleep: [0-1x10^6]\n NanoSleep: [0-1x10^9]\n"); + case ( EFAULT ) : return StandardException(loc, ecl::MemoryError, "Memory error."); + default : + { + std::ostringstream ostream; + ostream << "Unknown error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, UnknownError, ostream.str()); + } + } + +} + + +}; // namespace time +} // namespace ecl +#endif + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_TIME_SLEEP_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze.hpp new file mode 100644 index 0000000..58024d9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze.hpp @@ -0,0 +1,31 @@ +/** + * @file /include/ecl/time/snooze.hpp + * + * @brief Implements periodic loop timing via absolute time lookups. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SNOOZE_HPP_ +#define ECL_TIME_SNOOZE_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#if defined(ECL_IS_POSIX) + #include "snooze_pos.hpp" +#else + #include "snooze_win.hpp" +#endif + +#endif /* ECL_TIME_SNOOZE_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_pos.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_pos.hpp new file mode 100644 index 0000000..27cd957 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_pos.hpp @@ -0,0 +1,198 @@ +/** + * @file /include/ecl/time/snooze_pos.hpp + * + * @brief Periodic loop timers via the rt library. + * + * @date December 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SNOOZE_POS_HPP_ +#define ECL_TIME_SNOOZE_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "duration.hpp" +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Classes [Snooze] +*****************************************************************************/ + +/** + * @brief Implements periodic loop timing without the use of system timers. + * + * Intelligent use of the system's absolute time to do periodic timing + * without using up the system's timer/signal resources. It also manages + * to escape the effects of the following construct: + * \arg start loop + * \arg do work + * \arg get time + * \arg calculate remaining time + * \arg sleep remaining time + * \arg end loop + * The problem with this is a small amount of time drift creeps in. Additional + * latency may also occur between getting the time and sleeping due to + * scheduling of other processes. This class avoids this problem by sleeping + * until the next 'absolute time' which means the latency is only + * present on the very first loop. After that, only the effects of + * latency 'noise' will affect the looping. + * + * The only thing to be careful with this class is that the periodic + * timestamp does not get behind the current time. + * (this can happen because it was not initialised, or there was a burst of + * lag that causes the snooze class to not sleep at all for + * several loops until the timestamp catches up with the current time). + * + * By default the class is configured to validate the periodic timestamp + * every time the operator() is called. This will resync it with the + * current time if it gets behind. + * This however brings in a little latency as the snooze class has + * to make a call to check the current time. If this is an issue, + * you can set the validate variable to false in either the constructor + * or period() method. + * This will remove the validation, but ONLY do this if you are certain + * your loops will always be consistent (e.g. when scheduling the + * process/thread with SCHED_RR or SCHED_FIFO). + * + * Note that this is only really suitable for loops down to 1ms (best + * around 5-10ms or upwards). If you wish finer granularity, then you + * really need to consider a RTOS. + * + * Usage: + * + * @code + * Snooze snooze(Duration(0,20000000); // 20ms snooze + * // Some preliminaries + * snooze.initialise(); // make sure the snoozer is sync'ed with the current time. + * while (1) { + * // do some work + * snooze(); + * } + * @endcode + **/ +class ecl_time_PUBLIC Snooze { +public: + /********************* + ** C&D's + **********************/ + /** + * @brief Initialises the snoozer with a default period of 10ms. + * + * Default initialisation for the snooze class - 10ms periods and no validation. + * Use the period() method to reconfigure if desired. + */ + Snooze(); + /** + * @brief Initialises the snoozer RAII style with the specified period. + * + * Initialises the snoozer RAII style with the specified period. It also + * optionally allows the user to specify whether they want to validate + * each snooze timestamp so that it doesn't get behind the current time. + * Doing so increases the work the class needs to do though. By default + * the class does not validate so as to keep latency to a minimum, + * but use it like this with care. + * + * @param time : the period of the loop that will be used. + * @param validate : flag that enables validation of the latency at each loop. + **/ + Snooze (const Duration &time, const bool& validate = false ); + virtual ~Snooze() {} + + /********************* + ** Usage Methods + **********************/ + /** + * @brief Reconfigures the snoozer with the specified period. + * + * Reinitialises the snoozer with the specified period. It also + * optionally allows the user to specify whether they want to validate + * each snooze timestamp so that it doesn't get behind the current time. + * Doing so increases the work the class needs to do though. By default + * the class does not validate so as to keep latency to a minimum, + * but use it like this with care. + * + * @param time : the period of the loop that will be used. + * @param validate : flag that enables validation of the latency at each loop. + **/ + void period(const Duration &time, const bool& validate = false); + /** + * @brief Returns the currently configured period setting. + * + * Returns the currently configured period setting. + * + * @return Duration : the current time period duration. + **/ + Duration period() { return Duration(time_period.tv_sec,time_period.tv_nsec); } + /** + * @brief Restarts the snoozer (syncs it with the current time). + * + * Use this immediately before starting to loop (that is, if you haven't + * instantiated the class or called the period() function directly + * beforehand). + */ + void initialise(); + /** + * @brief Puts the thread/process to sleep until the next period is reached. + * + * Sleeps until the next periodic timestamp has been reached. If the + * timestamp has fallen behind the current time, it will react in one + * of two ways: + * + * - If validation checks were requested, it will resync with the current time. + * - Otherwise, it will simply return immediately. + */ + void operator()(); + +protected: + /********************* + ** Internal Methods + **********************/ + /** + * @brief Adds a period to the currently stored 'alarm clock' setting. + * + * Internally used to add the period to the time structure without causing + * problems while wrapping around. + */ + void add_period(); + /** + * @brief Validates that the snooze timestamp hasn't fallen behind the current time. + * + * Validate that the snooze timestamp has not fallen behind the current time. + * If it has, then update the snooze time value to the current time value and proceed. + */ + void validate(); + + /********************* + ** Internal Variables + **********************/ + TimeStructure time_value; + TimeStructure time_period; + long wrap_value_ns; + bool validate_times; + +}; + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_TIME_SNOOZE_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_win.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_win.hpp new file mode 100644 index 0000000..a13732c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/snooze_win.hpp @@ -0,0 +1,198 @@ +/** + * @file /include/ecl/time/snooze_win.hpp + * + * @brief Periodic loop timers via the rt library. + * + * @date April 2013 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_SNOOZE_WIN_HPP_ +#define ECL_TIME_SNOOZE_WIN_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "duration.hpp" +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Classes [Snooze] +*****************************************************************************/ + +/** + * @brief Implements periodic loop timing without the use of system timers. + * + * Intelligent use of the system's absolute time to do periodic timing + * without using up the system's timer/signal resources. It also manages + * to escape the effects of the following construct: + * \arg start loop + * \arg do work + * \arg get time + * \arg calculate remaining time + * \arg sleep remaining time + * \arg end loop + * The problem with this is a small amount of time drift creeps in. Additional + * latency may also occur between getting the time and sleeping due to + * scheduling of other processes. This class avoids this problem by sleeping + * until the next 'absolute time' which means the latency is only + * present on the very first loop. After that, only the effects of + * latency 'noise' will affect the looping. + * + * The only thing to be careful with this class is that the periodic + * timestamp does not get behind the current time. + * (this can happen because it was not initialised, or there was a burst of + * lag that causes the snooze class to not sleep at all for + * several loops until the timestamp catches up with the current time). + * + * By default the class is configured to validate the periodic timestamp + * every time the operator() is called. This will resync it with the + * current time if it gets behind. + * This however brings in a little latency as the snooze class has + * to make a call to check the current time. If this is an issue, + * you can set the validate variable to false in either the constructor + * or period() method. + * This will remove the validation, but ONLY do this if you are certain + * your loops will always be consistent (e.g. when scheduling the + * process/thread with SCHED_RR or SCHED_FIFO). + * + * Note that this is only really suitable for loops down to 1ms (best + * around 5-10ms or upwards). If you wish finer granularity, then you + * really need to consider a RTOS. + * + * Usage: + * + * @code + * Snooze snooze(Duration(0,20000000); // 20ms snooze + * // Some preliminaries + * snooze.initialise(); // make sure the snoozer is sync'ed with the current time. + * while (1) { + * // do some work + * snooze(); + * } + * @endcode + **/ +class ecl_time_PUBLIC Snooze { +public: + /********************* + ** C&D's + **********************/ + /** + * @brief Initialises the snoozer with a default period of 10ms. + * + * Default initialisation for the snooze class - 10ms periods and no validation. + * Use the period() method to reconfigure if desired. + */ + Snooze(); + /** + * @brief Initialises the snoozer RAII style with the specified period. + * + * Initialises the snoozer RAII style with the specified period. It also + * optionally allows the user to specify whether they want to validate + * each snooze timestamp so that it doesn't get behind the current time. + * Doing so increases the work the class needs to do though. By default + * the class does not validate so as to keep latency to a minimum, + * but use it like this with care. + * + * @param time : the period of the loop that will be used. + * @param validate : flag that enables validation of the latency at each loop. + **/ + Snooze (const Duration &time, const bool& validate = false ); + virtual ~Snooze() {} + + /********************* + ** Usage Methods + **********************/ + /** + * @brief Reconfigures the snoozer with the specified period. + * + * Reinitialises the snoozer with the specified period. It also + * optionally allows the user to specify whether they want to validate + * each snooze timestamp so that it doesn't get behind the current time. + * Doing so increases the work the class needs to do though. By default + * the class does not validate so as to keep latency to a minimum, + * but use it like this with care. + * + * @param time : the period of the loop that will be used. + * @param validate : flag that enables validation of the latency at each loop. + **/ + void period(const Duration &time, const bool& validate = false); + /** + * @brief Returns the currently configured period setting. + * + * Returns the currently configured period setting. + * + * @return Duration : the current time period duration. + **/ + Duration period() { return Duration(time_period.tv_sec,time_period.tv_nsec); } + /** + * @brief Restarts the snoozer (syncs it with the current time). + * + * Use this immediately before starting to loop (that is, if you haven't + * instantiated the class or called the period() function directly + * beforehand). + */ + void initialise(); + /** + * @brief Puts the thread/process to sleep until the next period is reached. + * + * Sleeps until the next periodic timestamp has been reached. If the + * timestamp has fallen behind the current time, it will react in one + * of two ways: + * + * - If validation checks were requested, it will resync with the current time. + * - Otherwise, it will simply return immediately. + */ + void operator()(); + +protected: + /********************* + ** Internal Methods + **********************/ + /** + * @brief Adds a period to the currently stored 'alarm clock' setting. + * + * Internally used to add the period to the time structure without causing + * problems while wrapping around. + */ + void add_period(); + /** + * @brief Validates that the snooze timestamp hasn't fallen behind the current time. + * + * Validate that the snooze timestamp has not fallen behind the current time. + * If it has, then update the snooze time value to the current time value and proceed. + */ + void validate(); + + /********************* + ** Internal Variables + **********************/ + TimeStructure time_value; + TimeStructure time_period; + long wrap_value_ns; + bool validate_times; + +}; + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_TIME_SNOOZE_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/stopwatch.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/stopwatch.hpp new file mode 100644 index 0000000..778f42f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/stopwatch.hpp @@ -0,0 +1,97 @@ +/** + * @file /include/ecl/time/stopwatch.hpp + * + * @brief Cross-platform header inclusions for the stopwatch class. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_STOPWATCH_HPP_ +#define ECL_STOPWATCH_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "timestamp.hpp" +#include "macros.hpp" + +#ifdef ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @brief A timepiece that emulates the functionality of a stopwatch. + * + * This uses the TimeStamp class as a means of recording time, splits and + * elapsed time. Its operation should be intuitive. + * + * This is only valid on platforms with a supporting timestamp implementation. + * + * Note that the stopwatch starts automatically, just use restart() if you + * wish to reset and start again. + * + * Usage: + * @code + * StopWatch stopwatch; + * TimeStamp time; + * time = stopwatch.split() + * cout << time << endl; + * time = stopwatch.elapsed() + * cout << time << endl; + * stopwatch.restart(); + * @endcode + **/ +class ecl_time_PUBLIC StopWatch +{ + public: + /** + * Default constructor that initialises the stopwatch with the current + * system time to use as a point of reference. + **/ + StopWatch(); + + virtual ~StopWatch() {} + /** + * @brief Restarts the stopwatch. + * + * Restarts the stopwatch (i.e. re-initialises the stopwatch with the + * current system time as its point of reference). + **/ + void restart(); + + /** + * @brief Calculates the total elapsed time. + * + * Calculates the total elapsed time since the stopwatch was started. + * @return TimeStamp : the total elapsed time since (re)started. + **/ + TimeStamp elapsed(); + /** + * @brief Calculates the current split. + * + * Calculates the elapsed time since the last split. + * @return TimeStamp : the elapsed time since the last split. + **/ + TimeStamp split(); + + private: + TimeStamp start_time, split_time; +}; + + +} // namespace ecl + +#endif /* ECL_HAS_TIMESTAMP */ +#endif /* ECL_STOPWATCH_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/time_data.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/time_data.hpp new file mode 100644 index 0000000..b6b496b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/time_data.hpp @@ -0,0 +1,80 @@ +/** + * @file /ecl_time/include/ecl/time/time_data.hpp + * + * @brief Device for conveniently storing and analysing benchmarking times. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ELC_TIME_TIME_DATA_HPP_ +#define ELC_TIME_TIME_DATA_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "duration.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [TimeData] +*****************************************************************************/ +/** + * @brief Device for conveniently storing and analysing benchmarking times. + * + * This serves as both a container and interface for generating statistics on + * a sequence of timings. + */ +class ecl_time_PUBLIC TimeData { +public: + /********************* + ** Collection + **********************/ + /** + * @brief Append a new timing measurement to the sequence. + * + * @param duration : measurement to be added. + */ + void push_back(const ecl::Duration& duration ) { durations.push_back(duration); } + /** + * @brief Reset the container (i.e. clear it). + */ + void clear() { durations.clear(); } + + /********************* + ** Statistics + **********************/ + /** + * @brief Return the average of the elements currently stored. + * @return Duration : average. + */ + ecl::Duration average() const; + /** + * @brief Return the standard deviation of the elements currently stored. + * @return Duration : standard deviation. + */ + ecl::Duration stdDev() const; + /** + * @brief Return the variance of the elements currently stored. + * @return Duration : variance. + */ + ecl::Duration variance() const; + +private: + std::vector durations; +}; + +} // namespace ecl + +#endif /* ELC_TIME_TIME_DATA_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp.hpp new file mode 100644 index 0000000..6ec98d2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp.hpp @@ -0,0 +1,34 @@ +/** + * @file /include/ecl/time/timestamp.hpp + * + * @brief Cross-platform header inclusions for the timestamp class. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_TIME_STAMP_HPP_ +#define ECL_TIME_TIME_STAMP_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +// Use the ecl cross platform time functions. +#include + +#if defined(ECL_IS_POSIX) + #include "timestamp_pos.hpp" +#elif defined(ECL_IS_WIN32) + #include "timestamp_win.hpp" +#endif + +#endif /* ECL_TIME_TIME_STAMP_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_base.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_base.hpp new file mode 100644 index 0000000..e16299b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_base.hpp @@ -0,0 +1,259 @@ +/** + * @file /ecl_time/include/ecl/time/timestamp_base.hpp + * + * @brief Base class with common functionality across platforms for timestamps. + * + * @date May 24, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_TIMESTAMP_BASE_HPP_ +#define ECL_TIME_TIMESTAMP_BASE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ +/** + * @brief This class provides common functionality across platforms for the timestamps. + * + * Most of the operations on a timestamp class is common from one platform + * to the next. These functions are bundled together in this class. + */ +class ecl_time_PUBLIC TimeStampBase { +public: + /********************* + ** Constructors + **********************/ + explicit TimeStampBase() {}; /**< @brief Default constructor. **/ + /** + * @brief Initialise the timestamp with a default value. + * + * Initialises the timestamp with the specified double value. Note that this is + * slower than the manual initialisation with a sec/nsec pair. + * + * @param decimal_time_value : time units in seconds (integral part) and nanoseconds (decimal part). + * + * @exception StandardException : throws if the input arguments is not positive [debug mode only]. + */ + explicit TimeStampBase (const double& decimal_time_value); + /** + * @brief Initialises the timestamp with the specified sec/nsec pair. + * + * This is the fastest means of initialisation to a set time value. + * + * @param seconds : discrete time value measured in whole seconds. + * @param nanoseconds : fraction of a second measured in nanoseconds. + * @exception StandardException : throws if input arguments are not positive [debug mode only]. + **/ + TimeStampBase (const time_t &seconds, const long &nanoseconds); + + virtual ~TimeStampBase() {} + + /****************************************** + ** Stamps + *******************************************/ + /** + * @brief Manually set the timestamp. + * + * Manually sets the timestamp with the specified double value. Note that this is + * slower than the stamp with a sec/nsec pair. + * + * @param decimal_time_value : time units in seconds (integral part) and nanoseconds (decimal part). + * + * @exception StandardException : throws if the input arguments is not positive [debug mode only]. + */ + const TimeStampBase& stamp (const double& decimal_time_value); + /** + * @brief Manually sets the timestamp with the specified values. + * + * This is the fastest way of setting the timestamp. + * + * @param seconds : discrete time value measured in whole seconds. + * @param nanoseconds : fraction of a second measured in nanoseconds. + * + * @exception StandardException : throws if input arguments are not positive [debug mode only]. + */ + const TimeStampBase& stamp (const time_t &seconds, const long &nanoseconds); + + /****************************************** + ** Accessors + *******************************************/ + /** + * @brief Seconds component. + * + * Get the current number of whole seconds recorded by this timestamp. + * @return Seconds : the number of whole seconds recorded by this timestamp. + */ + long sec() const { return time.tv_sec; } + /** + * @brief Milliseconds component (after removing seconds). + * + * Get the fractional number of milliseconds recorded in this timestamp. + * @return long : the fractional amount of time recorded by this timestamp (in ms). + */ + long msec() const { return time.tv_nsec/1000000L; } + /** + * @brief Microseconds component (after removing seconds). + * + * Get the fractional number of microseconds recorded in this timestamp. + * @return long : the fractional amount of time recorded by this timestamp (in us). + */ + long usec() const { return time.tv_nsec/1000; } + /** + * @brief Nanoseconds component (after removing seconds). + * + * Get the fractional number of nanoseconds recorded in this timestamp. + * @return long : the fractional amount of time recorded by this timestamp (in ns). + */ + long nsec() const { return time.tv_nsec; } + + /** + * @brief Disguises the timestamp as a regular double. + * + * Converts the posix timespec structure to a double (seconds->integral part, + * nanoseconds->fractional part). This is sometimes useful in time calculations. + */ + operator double() const { return ( time.tv_sec + time.tv_nsec*0.000000001); } + + /****************************************** + ** Comparison Operators + *******************************************/ + /** + * Equality operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator==(const TimeStampBase& time_stamp); + /** + * Inequality operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator!=(const TimeStampBase& time_stamp); + /** + * Less than or equal to operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator<=(const TimeStampBase& time_stamp); + /** + * Greater than or equal to operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator>=(const TimeStampBase& time_stamp); + /** + * Less than operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator<(const TimeStampBase& time_stamp); + /** + * Greater than or equal to operator. + * @param time_stamp : the rhv (timestamp) to be compared to this instance. + * @return bool : the result of the comparison operation. + */ + bool operator>(const TimeStampBase& time_stamp); + + /****************************************** + ** Mathematical Operators + *******************************************/ + /** + * Sum operator that returns a new timestamp holding the sum. + * @param time_stamp : the rhv (timestamp to be added to this instance). + * @return TimeStamp : the sum of the two timestamps. + */ + TimeStampBase operator+(const TimeStampBase& time_stamp ); + /** + * Sum operator that modifies this instance with the result. + * @param time_stamp : the rhv (timestamp to be added to this instance). + */ + void operator+=(const TimeStampBase& time_stamp); + /** + * Difference operator that returns a new timestamp holding the difference. + * Note that a difference that would result in a negative timestamp is not + * permitted (design requirement). Subsequently, this method will throw when + * in debug mode if this situation occurs. + * @param time_stamp : the rhv (timestamp to be subtracted from this instance). + * @return TimeStamp : the difference of the two timestamps. + * @exception StandardException : throws if difference would create a negative timestamp [debug mode only]. + */ + TimeStampBase operator-(const TimeStampBase& time_stamp ); + /** + * Difference operator that modifies this instance with the result. + * Note that a difference that would result in a negative timestamp is not + * permitted (design requirement). Subsequently, this method will throw when + * in debug mode if this situation occurs. + * @param time_stamp : the rhv (timestamp to be subtracted from this instance). + * @exception StandardException : throws if difference would create a negative timestamp [debug mode only]. + */ + void operator-=(const TimeStampBase& time_stamp); + + /****************************************** + ** Insertion Operator + *******************************************/ + template + friend OutputStream& operator << ( OutputStream &ostream , const TimeStampBase& time_stamp ); + +protected: + TimeStructure time; +}; + + +/***************************************************************************** +** Implementation [Insertion Operator] +*****************************************************************************/ + +template +OutputStream& operator <<( OutputStream &ostream , const TimeStampBase& time_stamp ) +{ + if ( ( time_stamp.time.tv_sec == 0 ) && (time_stamp.time.tv_nsec < 0 ) ) { + ostream << "-"; + } + ostream << time_stamp.time.tv_sec << "."; + long nanoseconds = std::abs(time_stamp.time.tv_nsec); + if ( nanoseconds < 10 ) { + ostream << "00000000"; + } else if ( nanoseconds < 100 ) { + ostream << "0000000"; + } else if ( nanoseconds < 1000 ) { + ostream << "000000"; + } else if ( nanoseconds < 10000 ) { + ostream << "00000"; + } else if ( nanoseconds < 100000 ) { + ostream << "0000"; + } else if ( nanoseconds < 1000000 ) { + ostream << "000"; + } else if ( nanoseconds < 10000000 ) { + ostream << "00"; + } else if ( nanoseconds < 100000000 ) { + ostream << "0"; + } + ostream << nanoseconds; + return ostream; +} + +} // namespace ecl + +#endif /* ECL_TIME_TIMESTAMP_BASE_HPP_ */ + + + diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_pos.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_pos.hpp new file mode 100644 index 0000000..70e23b1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_pos.hpp @@ -0,0 +1,186 @@ +/** + * @file /include/ecl/time/timestamp_pos.hpp + * + * @brief Interfaces for the posix/rt timers. + * + * @date June, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_STAMP_POS_HPP_ +#define ECL_TIME_STAMP_POS_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) +#define ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "timestamp_base.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface [Time] +*****************************************************************************/ + +/** + * @brief Posix timestamping class. + * + * This class works with the posix timespec struct that allows + * timestamping and operations on the time objects (differences etc). + * + * Usage: + * + * There are several ways of initialising the timestamp: + * @code + * TimeStamp time_system; // Automatically captures system time since Epoch. + * TimeStamp time_double(3.21) // Initialise with a decimalised time (slow). + * TimeStamp time_pair(3,210000000) // Initialise with a (s,ns) pair (fastest). + * @endcode + * + * These operations can also be performed to set the timestamp after construction: + * + * @code + * time_system.stamp(); // Automatically captures system time since Epoch. + * time_double.stamp(3.21) // Initialise with a decimalised time (slow). + * time_pair.stamp(3,210000000) // Initialise with a (s,ns) pair (fast for posix rt systems). + * @endcode + * + * All the usual comparison (==,!=,<=,>=,<,>) and mathematical (+,-,+=,-=) operations can also be used. + * + * @code + * if ( time_system > time_double ) { + * time_system -= time_double; + * } + * @endcode + * + * Caution: The only thing to be wary of with timestamps is to remember that they + * must always be positive. This was a design decision that keeps the timestamp class as light as + * possible. If negativity was introduced, an extra sign bit would be required, and in almost all + * timestamp operations, this is not necessary. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit/attempt to + * create a negative timestamp (more likely). + * + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + **/ +class ecl_time_PUBLIC TimeStamp : public TimeStampBase { +public: + /********************* + ** Constructors + **********************/ + /** + * @brief Initialises the timestamp with the current time. + * + * Constructor that initialises the timestamp with the current + * system time using the windows query performance calls (these call + * the intel handles under the hood). + * + * @exception StandardException : throws if clock lookup fails [debug mode only]. + **/ + TimeStamp(); + /** + * @brief Initialise the timestamp with a default value. + * + * Initialises the timestamp with the specified double value. Note that this is + * slower than the manual initialisation with a sec/nsec pair. + * + * @param decimal_time_value : time in decimal format (secs). + * + * @exception StandardException : thrown from TimeStampBase if the input arguments is not positive [debug mode only]. + */ + TimeStamp (const double& decimal_time_value); + /** + * @brief Initialises the timestamp with the specified sec/nsec pair. + * + * This is the fastest means of initialisation to a set time value. + * + * @param seconds : discrete time value measured in whole seconds. + * @param nanoseconds : fraction of a second measured in nanoseconds. + * + * @exception StandardException : thrown from TimeStampBase if input arguments are not positive [debug mode only]. + **/ + TimeStamp (const time_t &seconds, const long &nanoseconds); + /** + * @brief Allow direct conversions from the base class. + * + * Not for direct use - it is only there so that the operators that return a TimeStampBase + * class will correctly convert into their child class counterparts. As the children + * only contain methods, this loses nothing. + * + * @param base : the base class (data) representation. + */ + TimeStamp (const TimeStampBase& base); + + virtual ~TimeStamp() {} + + /****************************************** + ** Stamps + *******************************************/ + using TimeStampBase::stamp; + /** + * @brief Stamp with the system timestamp. + * + * Records the internal time variables with the current system time. + * @exception StandardException : throws if clock lookup fails [debug mode only]. + */ + const TimeStamp& stamp(); +#if defined(ECL_HAS_RT_TIMERS) + /** + * @brief Force use of the realtime clock (even if monotonic is available). + * + * This is not the preferred stamp and isn't intended to be a cross-platform + * option. Quite often 3rd party libraries (e.g. ros) do use this clock though, + * so to be compatible we provide the option here. + */ + static TimeStamp realtime_now(); +#endif +}; + + + +} // namespace ecl + +#ifdef ECL_HAS_EXCEPTIONS +namespace ecl { +namespace time { + +/** + * This function generates a custom StandardException response + * for posix error numbers generated by time.h function calls within + * the TimeStamp class. + * @param loc : use with the LOC macro, identifies the line and file of the code. + */ +ecl::StandardException throwTimeStampException(const char*loc); + +} // namespace time +} // namespace ecl + +#endif /* ECL_HAS_EXCEPTIONS */ + + +#endif /* ECL_IS_POSIX */ +#endif /* ECL_TIME_STAMP_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_win.hpp b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_win.hpp new file mode 100644 index 0000000..46e5769 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/include/ecl/time/timestamp_win.hpp @@ -0,0 +1,157 @@ +/** + * @file /ecl_time/include/ecl/time/timestamp_win.hpp + * + * @brief Interfaces for the time_stamp class utilising win timers. + * + * @date May 22, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_TIMESTAMP_WIN_HPP_ +#define ECL_TIME_TIMESTAMP_WIN_HPP_ + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) +#define ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "timestamp_base.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Interface +*****************************************************************************/ +/** + * @brief Win32 timestamping class. + * + * Windoze doesn't have a decent api for doing low resolution timestamping. + * Even though the resolution is fine with some of the methods, the sampling + * accuracy is really rough. One solution (which often has problems, particularly + * with AMD chips?, but its the best we've got to work with) is to use the + * queries directly to the intel cores. + * + * Usage: + * + * There are several ways of initialising the timestamp: + * @code + * TimeStamp time_system; // Automatically captures system time since Epoch. + * TimeStamp time_double(3.21) // Initialise with a decimalised time (slow). + * TimeStamp time_pair(3,210000000) // Initialise with a (s,ns) pair (fastest). + * @endcode + * + * These operations can also be performed to set the timestamp after construction: + * + * @code + * time_system.stamp(); // Automatically captures system time since Epoch. + * time_double.stamp(3.21) // Initialise with a decimalised time (slow). + * time_pair.stamp(3,210000000) // Initialise with a (s,ns) pair (fast for posix rt systems). + * @endcode + * + * All the usual comparison (==,!=,<=,>=,<,>) and mathematical (+,-,+=,-=) operations can also be used. + * + * @code + * if ( time_system > time_double ) { + * time_system -= time_double; + * } + * @endcode + * + * Caution: The only thing to be wary of with timestamps is to remember that they + * must always be positive. This was a design decision that keeps the timestamp class as light as + * possible. If negativity was introduced, an extra sign bit would be required, and in almost all + * timestamp operations, this is not necessary. + * + * Error Handling + * + * Will throw exceptions in debug mode if the timer doesn't initialise + * properly (unlikely) or you exceed the resolution of a time unit/attempt to + * create a negative timestamp (more likely). + * + * In release mode they do not come with any error handling. These functions + * need to remain fast, like containers, and since they're not usually + * destructive, such bells and whistles are omitted. + **/ +class ecl_time_PUBLIC TimeStamp : public TimeStampBase { +public: + /********************* + ** Constructors + **********************/ + /** + * @brief Initialises the timestamp with the current time. + * + * Constructor that initialises the timestamp with the current + * system time using the windows query performance calls (these call + * the intel handles under the hood). + * + * @exception StandardException : throws if clock lookup fails [debug mode only]. + **/ + TimeStamp(); + /** + * @brief Initialise the timestamp with a default value. + * + * Initialises the timestamp with the specified double value. Note that this is + * slower than the manual initialisation with a sec/nsec pair. + * + * @param decimal_time_value : time units in seconds (integral part) and nanoseconds (decimal part). + * + * @exception StandardException : thrown from TimeStampBase if the input arguments is not positive [debug mode only]. + */ + TimeStamp (const double& decimal_time_value); + /** + * @brief Initialises the timestamp with the specified sec/nsec pair. + * + * This is the fastest means of initialisation to a set time value. + * + * @param seconds : discrete time value measured in whole seconds. + * @param nanoseconds : fraction of a second measured in nanoseconds. + * + * @exception StandardException : thrown from TimeStampBase if input arguments are not positive [debug mode only]. + **/ + TimeStamp (const time_t &seconds, const long &nanoseconds); + /** + * @brief Allow direct conversions from the base class. + * + * Not for direct use - it is only there so that the operators that return a TimeStampBase + * class will correctly convert into their child class counterparts. As the children + * only contain methods, this loses nothing. + * + * @param base : the base class (data) representation. + */ + TimeStamp (const TimeStampBase& base); + + virtual ~TimeStamp() {} + + /****************************************** + ** Stamps + *******************************************/ + using TimeStampBase::stamp; + /** + * @brief Stamp with the system timestamp. + * + * Records the internal time variables with the current system time. + * @exception StandardException : throws if clock lookup fails [debug mode only]. + */ + const TimeStamp& stamp(); +}; + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ +#endif /* ECL_TIME_TIMESTAMP_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_time/package.xml b/ros2_ws/src/ecl_core/ecl_time/package.xml new file mode 100644 index 0000000..067c03b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/package.xml @@ -0,0 +1,45 @@ + + + ecl_time + 1.2.1 + + Timing utilities are very dependent on the system api provided for their use. + This package provides a means for handling different timing models. Current support + + - posix rt : complete. + - macosx : posix timers only, missing absolute timers. + - win : none. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_time + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_time_lite + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_exceptions + ecl_time_lite + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/src/CMakeLists.txt new file mode 100644 index 0000000..3c08c93 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() +add_subdirectory(examples) diff --git a/ros2_ws/src/ecl_core/ecl_time/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/src/examples/CMakeLists.txt new file mode 100644 index 0000000..0ba00c1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/examples/CMakeLists.txt @@ -0,0 +1,21 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_time_add_example name) + set(target_name ecl_time_example_${name}) + add_executable(${target_name} ${name}.cpp) + target_link_libraries(${target_name} + ${PROJECT_NAME} + ecl_config::ecl_config + ) + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ${target_name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_time_add_example(random_number_generator) +ecl_time_add_example(sleep) \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_time/src/examples/random_number_generator.cpp b/ros2_ws/src/ecl_core/ecl_time/src/examples/random_number_generator.cpp new file mode 100644 index 0000000..49898e4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/examples/random_number_generator.cpp @@ -0,0 +1,103 @@ +/** + * @file src/examples/random_number_generator.cpp + * + * @brief Demos the random number generator. + * + * @date July, 2014 + **/ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +#include +#include "../../include/ecl/time/random_number_generator.hpp" + +/***************************************************************************** + ** Main + *****************************************************************************/ + +int main() +{ + + ecl::RandomNumberGenerator random_number_generator; + int n = 5; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Uniform Numbers" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Default (0, 1):" << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.uniform(); + } + std::cout << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.uniform(); + } + std::cout << std::endl; + std::cout << "Over Range (-5, 5): " << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.uniform(5.0); + } + std::cout << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.uniform(5.0); + } + std::cout << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Guassian" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "std = 1, avg = 0: " << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(1.0); + } + std::cout << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(1.0); + } + std::cout << std::endl; + + std::cout << "std = 1, avg = 3: " << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(1.0, 3.0); + } + std::cout << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(1.0, 3.0); + } + std::cout << std::endl; + + std::cout << "std = 3, avg = 5: " << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(3.0, 5.0); + } + std::cout << std::endl; + for (int i = 0; i < n; ++i) + { + std::cout << " " << random_number_generator.gaussian(3.0, 5.0); + } + std::cout << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_time/src/examples/sleep.cpp b/ros2_ws/src/ecl_core/ecl_time/src/examples/sleep.cpp new file mode 100644 index 0000000..04981c0 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/examples/sleep.cpp @@ -0,0 +1,72 @@ +/** + * @file src/examples/sleep.cpp + * + * @brief Demos the sleep functions. + * + * @date April, 2011 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/sleep.hpp" + +int main() { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Sleep" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::Duration duration(1,300000000); + ecl::MilliSleep sleep; + ecl::MilliSleep sleep_ms; + ecl::MicroSleep sleep_us; + ecl::NanoSleep sleep_ns; + + std::cout << "Sleep: Duration 1s 300000000ns" << std::endl; + sleep(duration); + std::cout << "Sleep: 1s" << std::endl; + sleep(1); + std::cout << "MilliSleep: 500 x 2 = 1s" << std::endl; + for ( int i = 0; i < 2; ++i ) { sleep_ms(500); } + std::cout << "MicroSleep: 500,000 x 2 = 1s" << std::endl; + for ( int i = 0; i < 2; ++i ) { sleep_us(500000); } + std::cout << "NanoSleep: 500,000,000 x 2 = 1s" << std::endl; + for ( int i = 0; i < 2; ++i ) { sleep_ns(500000000); } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Pre Configured Sleep" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::Sleep sleep_1_3s(duration); + std::cout << "Sleep" << std::endl; + sleep_1_3s(); + ecl::MilliSleep sleep_1400ms(1400); + std::cout << "MilliSleep" << std::endl; + sleep_1400ms(); + ecl::MicroSleep sleep_1400us(1400); + std::cout << "MicroSleep" << std::endl; + sleep_1400us(); + ecl::NanoSleep sleep_1400ns(1400); + std::cout << "NanoSleep" << std::endl; + sleep_1400ns(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/src/lib/CMakeLists.txt new file mode 100644 index 0000000..c9b7fc2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/CMakeLists.txt @@ -0,0 +1,52 @@ +############################################################################### +# SOURCES +############################################################################### + +# Note, macro magic stops us compiling objects for the wrong implementations below +SET(SOURCES + cpuwatch_rt.cpp + frequency.cpp + sleep_win.cpp + sleep_pos.cpp + snooze_pos.cpp + snooze_win.cpp + stopwatch.cpp + timestamp_base.cpp + timestamp_pos.cpp + timestamp_win.cpp + time_data.cpp +) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors + ecl_exceptions::ecl_exceptions + ecl_time_lite::ecl_time_lite +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/cpuwatch_rt.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/cpuwatch_rt.cpp new file mode 100644 index 0000000..a78d51f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/cpuwatch_rt.cpp @@ -0,0 +1,72 @@ +/** + * @file /src/lib/cpuwatch_rt.cpp + * + * @brief Posix rt-timer implementation of the cpuwatch class. + * + * @date June, 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#if defined(ECL_IS_POSIX) + // monotonic clock, cpu clock -> clock_gettime; clock_selection -> clock_nanosleep + #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK) >= 0L && defined(_POSIX_CLOCK_SELECTION) && (_POSIX_CLOCK_SELECTION) >= 0L + + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time/cpuwatch_rt.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [CpuWatch] +*****************************************************************************/ + +CpuWatch::CpuWatch() { + cpu_time(tmp); + start_time.stamp(tmp.tv_sec, tmp.tv_nsec); + split_time = start_time; +} + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +void CpuWatch::restart() +{ + cpu_time(tmp); + start_time.stamp(tmp.tv_sec, tmp.tv_nsec); + split_time = start_time; +} + +TimeStamp CpuWatch::elapsed() +{ + cpu_time(tmp); + TimeStamp current_time(tmp.tv_sec, tmp.tv_nsec); + return ( current_time - start_time ); +} + +TimeStamp CpuWatch::split() +{ + TimeStamp last_time = split_time; + cpu_time(tmp); + split_time.stamp(tmp.tv_sec,tmp.tv_nsec); + return (split_time - last_time); +} + +} // namespace ecl + +#endif /* MANY POSIX TIME REQ'MENTS */ +#endif /* ECL_IS_POSIX */ + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/frequency.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/frequency.cpp new file mode 100644 index 0000000..ab693e2 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/frequency.cpp @@ -0,0 +1,95 @@ +/** + * @file /ecl_time/src/lib/frequency.cpp + */ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time/frequency.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +FrequencyMonitor::FrequencyMonitor( + const float& window_period, + const bool& use_realtime_clock +) +: current_diagnostics() +, incoming_counter(0) +, last_anyalsed() +, minimum_interval(100000.0) // something ridiculously large so the next interval will fall underneath it +, maximum_interval(0.0) +, period(window_period) +, use_realtime_clock(use_realtime_clock) +#if defined(ECL_HAS_RT_TIMERS) +, last_incoming((use_realtime_clock) ? ecl::TimeStamp::realtime_now() : ecl::TimeStamp()) +#else +, last_incoming(ecl::TimeStamp()) +#endif +{ +} + +void FrequencyMonitor::update() { + current_diagnostics.has_connection = true; + incoming_counter++; +#if defined(ECL_HAS_RT_TIMERS) + ecl::TimeStamp new_incoming = (use_realtime_clock) ? ecl::TimeStamp::realtime_now() : ecl::TimeStamp(); +#else + ecl::TimeStamp new_incoming = ecl::TimeStamp(); +#endif + ecl::TimeStamp time_since_last = new_incoming - last_incoming; + if ( time_since_last < minimum_interval ) { + minimum_interval = time_since_last; + } + if ( time_since_last > maximum_interval ) { + maximum_interval = time_since_last; + } + last_incoming = new_incoming; +} + +const FrequencyDiagnostics& FrequencyMonitor::analyse() { +#if defined(ECL_HAS_RT_TIMERS) + ecl::TimeStamp now = ecl::TimeStamp::realtime_now(); +#else + ecl::TimeStamp now = ecl::TimeStamp(); +#endif + ecl::TimeStamp interval = now - last_anyalsed; + + /// every two seconds, we update the status as follows + if( interval > period ) + { + last_anyalsed = now; + if (incoming_counter == 0 ) { + current_diagnostics.has_connection = false; + current_diagnostics.minimum_interval = ecl::TimeStamp(0.0); + current_diagnostics.maximum_interval = ecl::TimeStamp(0.0); + current_diagnostics.hz = 0.0; + } else { + current_diagnostics.has_connection = true; + current_diagnostics.minimum_interval = minimum_interval; + current_diagnostics.maximum_interval = maximum_interval; + current_diagnostics.hz = static_cast(incoming_counter) / interval; + + // clear temporary variables + incoming_counter = 0; + minimum_interval = ecl::TimeStamp(100000.0); // something ridiculously large so the next interval will fall underneath it + maximum_interval = ecl::TimeStamp(0.0); + } + } + // always update this one + current_diagnostics.last_incoming = last_incoming; + return current_diagnostics; +} + +/***************************************************************************** + ** Trailers + *****************************************************************************/ + +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_pos.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_pos.cpp new file mode 100644 index 0000000..db3764b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_pos.cpp @@ -0,0 +1,135 @@ +/** + * @file /src/lib/sleep_pos.cpp + * + * @brief Posix rt-timer implementation of the sleep classes. + * + * @date August 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/duration.hpp" +#include "../../include/ecl/time/sleep_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Sleep] +*****************************************************************************/ +Sleep::Sleep(const Duration &duration) { + required.tv_sec = duration.sec(); + required.tv_nsec = duration.nsec(); +} + +Sleep::Sleep(const unsigned long &seconds) { + required.tv_sec = seconds; + required.tv_nsec = 0; +} + +void Sleep::operator ()() { + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; +} + +void Sleep::operator ()(const Duration &duration) { + required.tv_sec = duration.sec(); + required.tv_nsec = duration.nsec(); + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +void Sleep::operator ()(const unsigned long &seconds) { + required.tv_sec = seconds; + required.tv_nsec = 0; + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +/***************************************************************************** +** Implementation [MilliSleep] +*****************************************************************************/ + +MilliSleep::MilliSleep(const unsigned long &milliseconds) { + required.tv_sec = milliseconds/1000; // integer division + required.tv_nsec = (milliseconds%1000)*1000000; +} + +void MilliSleep::operator ()() { + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +void MilliSleep::operator ()(const unsigned long &milliseconds) { + required.tv_sec = milliseconds/1000; // integer division + required.tv_nsec = (milliseconds%1000)*1000000; + // required.tv_nsec = 1000000*milli_seconds; + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +/***************************************************************************** +** Implementation [MicroSleep] +*****************************************************************************/ + +MicroSleep::MicroSleep(const unsigned long µseconds) { + required.tv_sec = microseconds/1000000; // integer division + required.tv_nsec = (microseconds%1000000)*1000; +} + +void MicroSleep::operator ()() { + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +void MicroSleep::operator ()(const unsigned long µ_seconds) { + required.tv_nsec = 1000*micro_seconds; + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +/***************************************************************************** +** Implementation [NanoSleep] +*****************************************************************************/ + +NanoSleep::NanoSleep(const unsigned long &nanoseconds) { + required.tv_sec = nanoseconds/1000000000; // integer division + required.tv_nsec = nanoseconds%1000000000; +} + +void NanoSleep::operator ()() { + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +void NanoSleep::operator ()(const unsigned long &nanoseconds) { + required.tv_nsec = nanoseconds; + int result = nanosleep(&required, &remaining); + ecl_assert_throw( result == 0, time::throwSleepException(LOC) ); + (void) result; // for unused variable warnings, in case the assert wasn't triggered +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_win.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_win.cpp new file mode 100644 index 0000000..de72073 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/sleep_win.cpp @@ -0,0 +1,129 @@ +/** + * @file /src/lib/sleep_win.cpp + * + * @brief Implementation of the sleep classes. + * + * @date April 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/duration.hpp" +#include "../../include/ecl/time/sleep_win.hpp" + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Sleep] +*****************************************************************************/ +Sleep::Sleep(const Duration &duration) { + required.tv_sec = duration.sec(); + required.tv_nsec = duration.nsec(); +} + +Sleep::Sleep(const unsigned long &seconds) { + required.tv_sec = seconds; + required.tv_nsec = 0; +} + +void Sleep::operator ()() { + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +void Sleep::operator ()(const Duration &duration) { + required.tv_sec = duration.sec(); + required.tv_nsec = duration.nsec(); + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +void Sleep::operator ()(const unsigned long &seconds) { + required.tv_sec = seconds; + required.tv_nsec = 0; + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +/***************************************************************************** +** Implementation [MilliSleep] +*****************************************************************************/ + +MilliSleep::MilliSleep(const unsigned long &milliseconds) { + required.tv_sec = milliseconds/1000; // integer division + required.tv_nsec = (milliseconds%1000)*1000000; +} + +void MilliSleep::operator ()() { + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +void MilliSleep::operator ()(const unsigned long &milliseconds) { + required.tv_sec = milliseconds/1000; // integer division + required.tv_nsec = (milliseconds%1000)*1000000; +// required.tv_nsec = 1000000*milli_seconds; + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +/***************************************************************************** +** Implementation [MicroSleep] +*****************************************************************************/ + +MicroSleep::MicroSleep(const unsigned long µseconds) { + required.tv_sec = microseconds/1000000; // integer division + required.tv_nsec = (microseconds%1000000)*1000; +} + +void MicroSleep::operator ()() { + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +void MicroSleep::operator ()(const unsigned long µ_seconds) { + required.tv_nsec = 1000*micro_seconds; + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +/***************************************************************************** +** Implementation [NanoSleep] +*****************************************************************************/ + +NanoSleep::NanoSleep(const unsigned long &nanoseconds) { + required.tv_sec = nanoseconds/1000000000; // integer division + required.tv_nsec = nanoseconds%1000000000; +} + +void NanoSleep::operator ()() { + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +void NanoSleep::operator ()(const unsigned long &nanoseconds) { + required.tv_nsec = nanoseconds; + TimeError result = sleep(required); + ecl_assert_throw(result == TimeError(NoError), time::throwSleepException(LOC)); +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_pos.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_pos.cpp new file mode 100644 index 0000000..40062b7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_pos.cpp @@ -0,0 +1,96 @@ +/** + * @file /src/lib/snooze_pos.cpp + * + * @brief Implementation of periodic timers. + * + * @date December 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/snooze_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Snooze] +*****************************************************************************/ + +Snooze::Snooze() { + period(Duration(0,10000000)); +} + +Snooze::Snooze(const Duration &time, const bool& validate) { period(time, validate); } + +void Snooze::period(const Duration &time, const bool& validate) { + validate_times = validate; + time_period.tv_sec = time.sec(); + time_period.tv_nsec = time.nsec(); + wrap_value_ns = 1000000000L-time_period.tv_nsec; + initialise(); +} + +void Snooze::initialise() { + epoch_time(time_value); +} + +void Snooze::operator()() { + + add_period(); + validate(); + sleep_until(time_value); +} + +void Snooze::add_period() { + + // Nanoseconds + if ( time_value.tv_nsec > wrap_value_ns ) { // wrap + time_value.tv_nsec = time_value.tv_nsec - wrap_value_ns; + time_value.tv_sec += 1; + } else { + time_value.tv_nsec += time_period.tv_nsec; + } + // Seconds + time_value.tv_sec += time_period.tv_sec; + + if ( validate_times ) { + validate(); + } +} + +void Snooze::validate() { + + TimeStructure time_current; + epoch_time(time_current); + + if ( time_current.tv_sec > time_value.tv_sec ) { + // Revalidate + time_value.tv_sec = time_current.tv_sec; + time_value.tv_nsec = time_current.tv_nsec; + add_period(); + } else if ( time_current.tv_sec == time_value.tv_sec ) { + if ( time_current.tv_nsec > time_value.tv_nsec ) { + // Revalidate + time_value.tv_sec = time_current.tv_sec; + time_value.tv_nsec = time_current.tv_nsec; + add_period(); + } + } +} + +} // namespace ecl + +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_win.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_win.cpp new file mode 100644 index 0000000..63a9f56 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/snooze_win.cpp @@ -0,0 +1,96 @@ +/** + * @file /src/lib/snooze_win.cpp + * + * @brief Implementation of periodic timers. + * + * @date April 2013 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/snooze_win.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Snooze] +*****************************************************************************/ + +Snooze::Snooze() { + period(Duration(0,10000000)); +} + +Snooze::Snooze(const Duration &time, const bool& validate) { period(time, validate); } + +void Snooze::period(const Duration &time, const bool& validate) { + validate_times = validate; + time_period.tv_sec = time.sec(); + time_period.tv_nsec = time.nsec(); + wrap_value_ns = 1000000000L-time_period.tv_nsec; + initialise(); +} + +void Snooze::initialise() { + epoch_time(time_value); +} + +void Snooze::operator()() { + + add_period(); + validate(); + sleep_until(time_value); +} + +void Snooze::add_period() { + + // Nanoseconds + if ( time_value.tv_nsec > wrap_value_ns ) { // wrap + time_value.tv_nsec = time_value.tv_nsec - wrap_value_ns; + time_value.tv_sec += 1; + } else { + time_value.tv_nsec += time_period.tv_nsec; + } + // Seconds + time_value.tv_sec += time_period.tv_sec; + + if ( validate_times ) { + validate(); + } +} + +void Snooze::validate() { + + TimeStructure time_current; + epoch_time(time_current); + + if ( time_current.tv_sec > time_value.tv_sec ) { + // Revalidate + time_value.tv_sec = time_current.tv_sec; + time_value.tv_nsec = time_current.tv_nsec; + add_period(); + } else if ( time_current.tv_sec == time_value.tv_sec ) { + if ( time_current.tv_nsec > time_value.tv_nsec ) { + // Revalidate + time_value.tv_sec = time_current.tv_sec; + time_value.tv_nsec = time_current.tv_nsec; + add_period(); + } + } +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/stopwatch.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/stopwatch.cpp new file mode 100644 index 0000000..7866c55 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/stopwatch.cpp @@ -0,0 +1,57 @@ +/** + * @file /src/lib/stopwatch.cpp + * + * @brief Posix rt-timer implementation of the stopwatch class. + * + * @date June, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time/timestamp.hpp" +#include "../../include/ecl/time/stopwatch.hpp" +#ifdef ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [StopWatch] +*****************************************************************************/ +StopWatch::StopWatch() { + // The variable start_time will automatically initialise with the current + // system time. +} + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +void StopWatch::restart() +{ + start_time.stamp(); + split_time = start_time; +} + +TimeStamp StopWatch::elapsed() +{ + TimeStamp current_time; // Automatically fetches the current system time. + return ( current_time - start_time ); +} + +TimeStamp StopWatch::split() +{ + TimeStamp last_time = split_time; + split_time.stamp(); + return (split_time - last_time); +} + +} // namespace ecl + +#endif /* ECL_HAS_TIMESTAMP */ + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/time_data.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/time_data.cpp new file mode 100644 index 0000000..e3b641f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/time_data.cpp @@ -0,0 +1,55 @@ +/** + * @file /ecl_time/src/lib/time_data.cpp + * + * @brief Implementation of the time data interface. + * + * @date September 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/time_data.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [TimeData] +*****************************************************************************/ + +ecl::Duration TimeData::average() const { + double sum = 0.0; + for ( unsigned int i = 0; i < durations.size(); ++i ) { + sum += durations[i]; + } + return ecl::Duration(sum/static_cast(durations.size())); +} + +ecl::Duration TimeData::stdDev() const { + ecl::Duration avg = average(); + double sum = 0.0; + for ( unsigned int i = 0; i < durations.size(); ++i ) { + sum += (static_cast(durations[i]) - static_cast(avg))* + (static_cast(durations[i]) - static_cast(avg)); + } + return ecl::Duration(sqrt(sum/static_cast(durations.size()))); +} + +ecl::Duration TimeData::variance() const { + ecl::Duration avg = average(); + double sum = 0.0; + for ( unsigned int i = 0; i < durations.size(); ++i ) { + sum += (static_cast(durations[i]) - static_cast(avg))* + (static_cast(durations[i]) - static_cast(avg)); + } + return ecl::Duration(sum/static_cast(durations.size())); +} + +} // namespace ecl + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_base.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_base.cpp new file mode 100644 index 0000000..cec3c31 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_base.cpp @@ -0,0 +1,203 @@ +/** + * @file /ecl_time/src/lib/timestamp_base.cpp + * + * @brief Implementation of the common cross-functionality in timestamp. + * + * @date May 24, 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/time/timestamp_base.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +TimeStampBase::TimeStampBase (const double& decimal_time_value) +{ + time.tv_sec = static_cast(decimal_time_value); + time.tv_nsec = (decimal_time_value - static_cast(decimal_time_value))*1000000000L; +} + +TimeStampBase::TimeStampBase (const time_t& seconds, const long& nanoseconds) { + ecl_assert_throw( ( (seconds > 0) && (nanoseconds >= 0) ) || + ( (seconds < 0) && (nanoseconds <= 0) ) || + ( (seconds == 0) ), + StandardException(LOC,InvalidInputError,"Positive timestamps require positive nanoseconds, negative timestamps require negative nanoseconds.") ); + time.tv_sec = seconds; + time.tv_nsec = nanoseconds; +} + +/***************************************************************************** +** Implementation [Stamps] +*****************************************************************************/ + +const TimeStampBase& TimeStampBase::stamp (const double& decimal_time_value) { + time.tv_sec = static_cast(decimal_time_value); + time.tv_nsec = (decimal_time_value - static_cast(decimal_time_value))*1000000000L; + return (*this); +} + +const TimeStampBase& TimeStampBase::stamp (const time_t& seconds, const long& nanoseconds) { + ecl_assert_throw( ( (seconds > 0) && (nanoseconds >= 0) ) || + ( (seconds < 0) && (nanoseconds <= 0) ) || + ( (seconds == 0) ), + StandardException(LOC,InvalidInputError,"Positive timestamps require positive nanoseconds, negative timestamps require negative nanoseconds.") ); + time.tv_sec = seconds; + time.tv_nsec = nanoseconds; + return (*this); +} + +/***************************************************************************** +** Implementation [Comparison Operators] +*****************************************************************************/ + +bool TimeStampBase::operator==(const TimeStampBase& time_stamp ) { + if( ( time_stamp.time.tv_sec == time.tv_sec ) && ( time_stamp.time.tv_nsec == time.tv_nsec ) ) { + return true; + } else { + return false; + } +} + +bool TimeStampBase::operator!=(const TimeStampBase& time_stamp ) { + if( ( time_stamp.time.tv_sec == time.tv_sec ) && ( time_stamp.time.tv_nsec == time.tv_nsec ) ) { + return false; + } else { + return true; + } +} + +bool TimeStampBase::operator<=(const TimeStampBase& time_stamp ) { + if( time.tv_sec > time_stamp.time.tv_sec ) { + return false; + } else if ( time.tv_sec == time_stamp.time.tv_sec ) { + if ( time.tv_nsec > time_stamp.time.tv_nsec ) { + return false; + } + } + return true; +} + +bool TimeStampBase::operator>=(const TimeStampBase& time_stamp ) { + if( time.tv_sec < time_stamp.time.tv_sec ) { + return false; + } else if ( time.tv_sec == time_stamp.time.tv_sec ) { + if ( time.tv_nsec < time_stamp.time.tv_nsec ) { + return false; + } + } + return true; +} + +bool TimeStampBase::operator<(const TimeStampBase& time_stamp ) { + if( time.tv_sec > time_stamp.time.tv_sec ) { + return false; + } else if ( time.tv_sec == time_stamp.time.tv_sec ) { + if ( time.tv_nsec >= time_stamp.time.tv_nsec ) { + return false; + } + } + return true; +} + +bool TimeStampBase::operator>(const TimeStampBase& time_stamp ) { + if( time.tv_sec < time_stamp.time.tv_sec ) { + return false; + } else if ( time.tv_sec == time_stamp.time.tv_sec ) { + if ( time.tv_nsec <= time_stamp.time.tv_nsec ) { + return false; + } + } + return true; +} +/***************************************************************************** +** Implementation [TimeStamp][Mathematical Operators] +*****************************************************************************/ + +void TimeStampBase::operator+=(const TimeStampBase& time_stamp ) { + time.tv_sec += time_stamp.time.tv_sec; + int64 nsec = time.tv_nsec + time_stamp.time.tv_nsec; + if ( nsec >= 1000000000L ) { + time.tv_sec += 1; + nsec -= 1000000000L; + } else if ( nsec <= -1000000000L ) { + time.tv_sec -= 1; + nsec += 1000000000L; + } + if ( ( time.tv_sec > 0 ) && ( nsec < 0 ) ) { + time.tv_sec -= 1; + nsec = 1000000000L + nsec; + } + if ( ( time.tv_sec < 0 ) && ( nsec > 0 ) ) { + time.tv_sec += 1; + nsec = nsec - 1000000000L; + } + time.tv_nsec = nsec; +} + +TimeStampBase TimeStampBase::operator+(const TimeStampBase& time_stamp ) { + long sec = time.tv_sec + time_stamp.time.tv_sec; + int64 nsec = time.tv_nsec + time_stamp.time.tv_nsec; + if ( nsec >= 1000000000L ) { + sec += 1; + nsec -= 1000000000L; + } else if ( nsec <= -1000000000L ) { + sec -= 1; + nsec += 1000000000L; + } + if ( ( sec > 0 ) && ( nsec < 0 ) ) { + sec -= 1; + nsec = 1000000000L + nsec; + } + if ( ( sec < 0 ) && ( nsec > 0 ) ) { + sec += 1; + nsec = nsec - 1000000000L; + } + return TimeStampBase(sec,nsec); +} + +void TimeStampBase::operator-=(const TimeStampBase& time_stamp ) { + time_t sec = time.tv_sec - time_stamp.time.tv_sec; + long nsec = time.tv_nsec - time_stamp.time.tv_nsec; + + if ( (sec > 0) && ( nsec < 0 )) { + sec -= 1; + nsec += 1000000000L; + } else if ( (sec < 0) && ( nsec > 0 )) { + sec += 1; + nsec -= 1000000000L; + } + time.tv_sec = sec; + time.tv_nsec = nsec; +} + +TimeStampBase TimeStampBase::operator-(const TimeStampBase& time_stamp ) { + time_t sec = time.tv_sec - time_stamp.time.tv_sec; + long nsec = time.tv_nsec - time_stamp.time.tv_nsec; + + if ( (sec > 0) && ( nsec < 0 )) { + sec -= 1; + nsec += 1000000000L; + } else if ( (sec < 0) && ( nsec > 0 )) { + sec += 1; + nsec -= 1000000000L; + } + return TimeStampBase(sec,nsec); +} + + + +} // namespace ecl + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_pos.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_pos.cpp new file mode 100644 index 0000000..fd1592c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_pos.cpp @@ -0,0 +1,99 @@ +/** + * @file /src/lib/timestamp_pos.cpp + * + * @brief Posix rt-timer implementation of the timestamp class. + * + * @date May 2009 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "../../include/ecl/time/timestamp_pos.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [TimeStamp] +*****************************************************************************/ + +TimeStamp::TimeStamp() { + stamp(); +} + +TimeStamp::TimeStamp (const double& decimal_time_value) : + TimeStampBase(decimal_time_value) +{} + +TimeStamp::TimeStamp (const time_t& seconds, const long& nanoseconds) : + TimeStampBase(seconds, nanoseconds) +{} + +TimeStamp::TimeStamp(const TimeStampBase& base) : TimeStampBase(base) {} + +/***************************************************************************** +** Implementation [Stamps] +*****************************************************************************/ + +const TimeStamp& TimeStamp::stamp() { + if ( epoch_time(time).flag() != NoError ) { + ecl_debug_throw(time::throwTimeStampException(LOC)); + } + return (*this); +} + +#if defined(ECL_HAS_RT_TIMERS) +TimeStamp TimeStamp::realtime_now() { + TimeStructure time; + if ( realtime_epoch_time(time).flag() != NoError ) { + ecl_debug_throw(time::throwTimeStampException(LOC)); + } + return TimeStamp(time.tv_sec, time.tv_nsec); +} +#endif +} // namespace ecl + +/***************************************************************************** +** Implementation [Exceptions] +*****************************************************************************/ + +#ifdef ECL_HAS_EXCEPTIONS +namespace ecl { +namespace time { + +StandardException throwTimeStampException(const char* loc) { + int error_result = errno; + switch (error_result) { + case ( EINVAL ) : return ecl::StandardException(loc, ecl::NotSupportedError, "The requested clock is not supported on this system."); + case ( EFAULT ) : return ecl::StandardException(loc, ecl::OutOfRangeError, "The timespec pointer points outside the address space."); + default : + { + std::ostringstream ostream; + ostream << "Unknown posix error " << error_result << ": " << strerror(error_result) << "."; + return StandardException(loc, ecl::UnknownError, ostream.str()); + } + } +} + +} // namespace time +} // namespace ecl + +#endif /* ECL_HAS_EXCEPTIONS */ +#endif /* ECL_IS_POSIX */ diff --git a/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_win.cpp b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_win.cpp new file mode 100644 index 0000000..6b9ac4a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/lib/timestamp_win.cpp @@ -0,0 +1,73 @@ +/** + * @file /ecl_time/src/lib/timestamp_win.cpp + * + * @brief Windows implementation of the timestamp class. + * + * @date May 22, 2010 + **/ +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include +#if defined(ECL_IS_WIN32) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/time/timestamp_win.hpp" +// #include "../../include/ecl/time/detail/time_functions_win.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation [Constructors] +*****************************************************************************/ + +// TODO: check if chrono is compatible for both linux and win now, we can +// probably collapse them, and even remove some of the functions from +// time_functions_win.hpp +TimeStamp::TimeStamp() { + std::chrono::high_resolution_clock clock; + auto now = clock.now(); + + auto time_since_epoch = now.time_since_epoch(); + auto seconds = std::chrono::duration_cast(time_since_epoch); + auto num_seconds = seconds.count(); + auto num_nanoseconds = time_since_epoch.count() % 1000000000; + + time.tv_sec = num_seconds; + time.tv_nsec = num_nanoseconds; +} + +TimeStamp::TimeStamp (const double& decimal_time_value) : + TimeStampBase(decimal_time_value) +{ +} + +TimeStamp::TimeStamp (const time_t& seconds, const long& nanoseconds) : + TimeStampBase(seconds, nanoseconds) +{ +} + +TimeStamp::TimeStamp(const TimeStampBase& base) : TimeStampBase(base) {} + +/***************************************************************************** +** Implementation [Stamps] +*****************************************************************************/ + +const TimeStamp& TimeStamp::stamp() { + return (*this); +} + +} // namespace ecl + +#endif /* ECL_IS_WIN32 */ diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_time/src/test/CMakeLists.txt new file mode 100644 index 0000000..10f90d5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/CMakeLists.txt @@ -0,0 +1,23 @@ +############################################################################### +# Test Macro +############################################################################### + +macro(ecl_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Google Tests +############################################################################### + +ecl_add_gtest(cpuwatch_rt) +ecl_add_gtest(frequency) +ecl_add_gtest(sleep) +ecl_add_gtest(snooze) +ecl_add_gtest(timestamp) +ecl_add_gtest(time_data) +ecl_add_gtest(stopwatch) diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/cpuwatch_rt.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/cpuwatch_rt.cpp new file mode 100644 index 0000000..4280208 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/cpuwatch_rt.cpp @@ -0,0 +1,61 @@ +/** + * @file /src/test/cpuwatch_rt.cpp + * + * @brief Unit Test for the CpuWatch class. + * + * @date September 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/cpuwatch.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#include + +#if defined(ECL_IS_POSIX) + // monotonic clock, cpu clock -> clock_gettime; clock_selection -> clock_nanosleep + #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK) >= 0L && defined(_POSIX_CLOCK_SELECTION) && (_POSIX_CLOCK_SELECTION) >= 0L + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::CpuWatch; +using ecl::TimeStamp; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(StopwatchTests,silent) { + + CpuWatch stopwatch; + TimeStamp time; + + time = stopwatch.split(); + time = stopwatch.split(); + time = stopwatch.elapsed(); + // Can't really verify stuff, so this is just a unit test to make sure + // it compiles. + SUCCEED(); +} + + #endif /* MANY POSIX TIME REQ'MENTS */ +#endif /* ECL_IS_POSIX */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/frequency.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/frequency.cpp new file mode 100644 index 0000000..6736858 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/frequency.cpp @@ -0,0 +1,80 @@ +/** + * @file /src/test/frequency.cpp + * + * @brief Unit Test for the FrequncyMonitor class. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/time/frequency.hpp" +#include "../../include/ecl/time/sleep.hpp" +#include "../../include/ecl/time/timestamp.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#ifdef ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Methods +*****************************************************************************/ + +std::ostream& operator <<( std::ostream& ostream , const ecl::FrequencyDiagnostics& diagnostics ) +{ + ostream << std::fixed; + ostream << "hz : " << diagnostics.hz; + ostream << ", min : " << diagnostics.minimum_interval; + ostream << ", max : " << diagnostics.maximum_interval; + ostream << ", last_incoming : " << diagnostics.last_incoming << std::scientific; + // could print the others, but that would require use of std ios flags to pretty print correctly. + // let the user do that how they wish if they want to + return ostream; +} + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(FrequencyMonitorTests,silent) { + + ecl::FrequencyMonitor monitor(0.5, true); + ecl::FrequencyDiagnostics diagnostics; + + ecl::MilliSleep sleep_ms; + unsigned int period = 100; + +// std::cout << "\n**********************************************************" << std::endl; +// std::cout << "* Frequency Monitor Test" << std::endl; +// std::cout << "**********************************************************\n" << std::endl; + float epsilon = 0.3; + for ( unsigned int i = 0; i < 50; ++i ) { + monitor.update(); + diagnostics = monitor.analyse(); + if ( i == 25 ) { + period = 200; + std::cout << diagnostics << std::endl; + EXPECT_NEAR(diagnostics.hz, 10.0, epsilon); + } + sleep_ms(period); + } + std::cout << diagnostics << std::endl; + EXPECT_NEAR(diagnostics.hz, 5.0, epsilon); + SUCCEED(); +} + +#endif /* ECL_HAS_TIMESTAMP */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/sleep.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/sleep.cpp new file mode 100644 index 0000000..48f6f10 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/sleep.cpp @@ -0,0 +1,81 @@ +/** + * @file /src/test/sleep.cpp + * + * @brief Unit Test for the sleepers. + * + * @date August 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +//#include +#include +#include "../../include/ecl/time/sleep.hpp" +#include "../../include/ecl/time/timestamp.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +// Only posix implementation so far +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Duration; +using ecl::Sleep; +using ecl::MilliSleep; +using ecl::MicroSleep; +using ecl::NanoSleep; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SleepTests,sleepConfigured) { + + Duration duration(1,300000000); + Sleep sleep; + MilliSleep sleep_ms; + MicroSleep sleep_us; + NanoSleep sleep_ns; + + sleep(duration); + sleep(1); + sleep_ms(500); + sleep_us(500000); + sleep_ns(500000000); + + SUCCEED(); +} + +TEST(SleepTests,sleepPreConfigured) { + Duration duration(1,300000000); + Sleep sleep_1_3s(duration); + sleep_1_3s(); + MilliSleep sleep_1400ms(1400); + sleep_1400ms(); + MicroSleep sleep_1400us(1400); + sleep_1400us(); + NanoSleep sleep_1400ns(1400); + sleep_1400ns(); + SUCCEED(); +} + +#endif /* ECL_IS_POSIX */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/snooze.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/snooze.cpp new file mode 100644 index 0000000..368c80c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/snooze.cpp @@ -0,0 +1,80 @@ +/** + * @file /src/test/snooze.cpp + * + * @brief Unit Test for the snoozer. + * + * @date April 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +//#include +#include +#include "../../include/ecl/time/snooze.hpp" +#include "../../include/ecl/time/timestamp.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +// Only posix implementation so far +#include +#if defined(ECL_IS_POSIX) + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Duration; +using ecl::Snooze; +using ecl::TimeStamp; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(SnoozeTests,snoozeConfigured) { + // should check for exceptions here? + Duration duration(0.5); + Snooze snooze; + snooze.period(duration); + Snooze snooze_from_duration(duration); + Snooze snooze_with_validation(duration, true); + + SUCCEED(); +} + +TEST(SnoozeTests,setGetPeriod) { + Duration duration(0.5); + Snooze snooze; + snooze.period(duration); + double period = snooze.period(); + EXPECT_FLOAT_EQ(0.5,period); +} + +TEST(SnoozeTests,snooze) { + Duration duration(0.5); + Snooze snooze(duration); + TimeStamp start, finish; + snooze.initialise(); + snooze(); + finish.stamp(); + double difference = finish - start; + EXPECT_LT(0.5, difference); + EXPECT_GT(1.0, difference); +} + +#endif /* ECL_IS_POSIX */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/stopwatch.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/stopwatch.cpp new file mode 100644 index 0000000..af624df --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/stopwatch.cpp @@ -0,0 +1,57 @@ +/** + * @file /src/test/stopwatch.cpp + * + * @brief Unit Test for the StopWatch class. + * + * @date July, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/time/timestamp.hpp" +#include "../../include/ecl/time/stopwatch.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#ifdef ECL_HAS_TIMESTAMP + + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::StopWatch; +using ecl::TimeStamp; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(StopwatchTests,silent) { + + StopWatch stopwatch; + TimeStamp time; + + time = stopwatch.split(); + time = stopwatch.split(); + time = stopwatch.elapsed(); + + SUCCEED(); +} + +#endif /* ECL_HAS_TIMESTAMP */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/time_data.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/time_data.cpp new file mode 100644 index 0000000..4ee1c12 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/time_data.cpp @@ -0,0 +1,62 @@ +/** + * @file /src/test/timestamp.cpp + * + * @brief Unit Test for timestamp objects. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/time/time_data.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Duration; +using ecl::TimeData; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TimeDataTests,container) { + TimeData time_data; + Duration duration; + duration.stamp(1,0); + time_data.push_back(duration); + time_data.push_back(duration); + time_data.clear(); + SUCCEED(); +} + +TEST(TimeDataTests,statistics) { + TimeData time_data; + Duration duration; + duration.stamp(1,0); + time_data.push_back(duration); + duration.stamp(2,0); + time_data.push_back(duration); + double avg = time_data.average(); + EXPECT_LT(1.49,avg); // Allow for some roundoff error. + EXPECT_GT(1.51,avg); + double std_dev = time_data.stdDev(); + EXPECT_LT(0.49,std_dev); // Allow for some roundoff error. + EXPECT_GT(0.51,std_dev); + double variance = time_data.variance(); + EXPECT_LT(0.24,variance); // Allow for some roundoff error. + EXPECT_GT(0.26,variance); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_time/src/test/timestamp.cpp b/ros2_ws/src/ecl_core/ecl_time/src/test/timestamp.cpp new file mode 100644 index 0000000..6a73844 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_time/src/test/timestamp.cpp @@ -0,0 +1,363 @@ +/** + * @file /src/test/timestamp.cpp + * + * @brief Unit Test for timestamp objects. + * + * @date May 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/time/timestamp.hpp" + +/***************************************************************************** +** Platform Check +*****************************************************************************/ + +#ifdef ECL_HAS_TIMESTAMP + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::TimeStamp; + +/***************************************************************************** +** Variables +*****************************************************************************/ + +bool verbose = false; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TimeStampTests,construction) { + TimeStamp time; + SUCCEED(); + TimeStamp time_pair(3,123456789L); + EXPECT_FLOAT_EQ(3.123456789,time_pair); + TimeStamp time_double(3.00001); + EXPECT_FLOAT_EQ(3.00001,time_double); +} + +TEST(TimeStampTests,timestamps) { + TimeStamp time; + time.stamp(); + long t = time.sec(); + (void)t; + t = time.msec(); + (void)t; + t = time.usec(); + (void)t; + t = time.nsec(); + (void)t; + SUCCEED(); + time.stamp(3,1425); + EXPECT_FLOAT_EQ(3.000001425,time); + time.stamp(4.00000142); + EXPECT_FLOAT_EQ(4.00000142,time); +} + +TEST(TimeStampTests,copyConstruction) { + TimeStamp time(3,100); + TimeStamp time_copy(time); + EXPECT_EQ(3,time_copy.sec()); + EXPECT_EQ(100,time_copy.nsec()); +} + +TEST(TimeStampTests,copyAssignment) { + TimeStamp time(3,100); + TimeStamp time_copy; + time_copy = time; + EXPECT_EQ(3,time_copy.sec()); + EXPECT_EQ(100,time_copy.nsec()); +} + +TEST(TimeStampTests,comparisonOperators) { + TimeStamp time(3,100); + TimeStamp time_copy(time); + EXPECT_TRUE(time==time_copy); + EXPECT_FALSE(time!=time_copy); + EXPECT_TRUE(time<=time_copy); + EXPECT_TRUE(time>=time_copy); + EXPECT_FALSE(timetime_copy); + time.stamp(); + EXPECT_FALSE(time==time_copy); + EXPECT_TRUE(time!=time_copy); + EXPECT_FALSE(time<=time_copy); + EXPECT_TRUE(time>=time_copy); + EXPECT_FALSE(timetime_copy); +} + +TEST(TimeStampTests,mathematicalOperators) { + TimeStamp time, time_copy; + time.stamp(1,100100100L); + time_copy.stamp(1,900100100L); + time += time_copy; + EXPECT_EQ(3,time.sec()); + EXPECT_EQ(200200,time.nsec()); + time.stamp(1,100100100L); + time = time + time_copy; + EXPECT_EQ(3,time.sec()); + EXPECT_EQ(200200,time.nsec()); + time.stamp(2,100100100L); + time -= time_copy; + EXPECT_EQ(0,time.sec()); + EXPECT_EQ(200000000,time.nsec()); + time.stamp(2,100100100L); + time = time - time_copy; + EXPECT_EQ(0,time.sec()); + EXPECT_EQ(200000000,time.nsec()); +} + +TEST(TimeStampTests,negatives) { + if ( verbose ) { + std::cout << "*****************************************************************************" << std::endl; + std::cout << "* Negatives" << std::endl; + std::cout << "*****************************************************************************" << std::endl; + } + /**************************************** + ** Variables + ****************************************/ + ecl::TimeStamp time_2_3(2,300000000L), time_n_2_3(-2, -300000000L); + ecl::TimeStamp time_1_3(1,300000000L), time_n_1_3(-1,-300000000L); + ecl::TimeStamp time_0_3(0,300000000L), time_n_0_3(0,-300000000L); + ecl::TimeStamp time_2_7(2,700000000L), time_n_2_7(-2,-700000000L); + ecl::TimeStamp time_1_7(1,700000000L), time_n_1_7(-1,-700000000L); + ecl::TimeStamp time_0_7(0,700000000L), time_n_0_7(0,-700000000L); + /**************************************** + ** Constructor & Operator << + ****************************************/ + std::vector timestamps = { TimeStamp(1.7), + TimeStamp(0.7), + TimeStamp(-0.7), + TimeStamp(-1.7), + }; + if ( verbose ) { + std::cout << "Operator <<\n "; + for ( const TimeStamp& timestamp : timestamps) { + std::cout << timestamp << " "; + } + std::cout << std::endl; + } + EXPECT_EQ(1, timestamps[0].sec()); + EXPECT_EQ(700000000, timestamps[0].nsec()); + EXPECT_EQ(0, timestamps[1].sec()); + EXPECT_EQ(700000000, timestamps[1].nsec()); + EXPECT_EQ(0, timestamps[2].sec()); + EXPECT_EQ(-700000000, timestamps[2].nsec()); + EXPECT_EQ(-1, timestamps[3].sec()); + EXPECT_EQ(-700000000, timestamps[3].nsec()); + + std::vector double_representations; + for ( const TimeStamp& timestamp : timestamps) { + double_representations.push_back(timestamp); + } + if ( verbose ) { + std::cout << "Operator double()\n "; + for ( const float& d : double_representations ) { + std::cout << d << " "; + } + std::cout << std::endl; + } + EXPECT_FLOAT_EQ(1.7, double_representations[0]); + EXPECT_FLOAT_EQ(0.7, double_representations[1]); + EXPECT_FLOAT_EQ(-0.7, double_representations[2]); + EXPECT_FLOAT_EQ(-1.7, double_representations[3]); + + /**************************************** + ** Operator - + ****************************************/ + double_representations.clear(); + double_representations.push_back(ecl::TimeStamp(1.3) - ecl::TimeStamp(5.1)); + double_representations.push_back(ecl::TimeStamp(1.3) - ecl::TimeStamp(5.8)); + double_representations.push_back(ecl::TimeStamp(1.3) - ecl::TimeStamp(1.5)); + double_representations.push_back(ecl::TimeStamp(-1.3) - ecl::TimeStamp(1.5)); + double_representations.push_back(ecl::TimeStamp(-1.3) - ecl::TimeStamp(-0.8)); + double_representations.push_back(ecl::TimeStamp(-1.3) - ecl::TimeStamp(-5.8)); + if ( verbose ) { + std::cout << "Operator -\n "; + std::cout << (ecl::TimeStamp(1.3) - ecl::TimeStamp(5.1)) << " "; + std::cout << (ecl::TimeStamp(1.3) - ecl::TimeStamp(5.8)) << " "; + std::cout << (ecl::TimeStamp(1.3) - ecl::TimeStamp(1.5)) << " "; + std::cout << (ecl::TimeStamp(-1.3) - ecl::TimeStamp(1.5)) << " "; + std::cout << (ecl::TimeStamp(-1.3) - ecl::TimeStamp(-0.8)) << " "; + std::cout << (ecl::TimeStamp(-1.3) - ecl::TimeStamp(-5.8)) << " "; + std::cout << std::endl; + } + EXPECT_FLOAT_EQ(-3.8, double_representations[0]); + EXPECT_FLOAT_EQ(-4.5, double_representations[1]); + EXPECT_FLOAT_EQ(-0.2, double_representations[2]); + EXPECT_FLOAT_EQ(-2.8, double_representations[3]); + EXPECT_FLOAT_EQ(-0.5, double_representations[4]); + EXPECT_FLOAT_EQ(4.5, double_representations[5]); + + /**************************************** + ** Operator -= + ****************************************/ + double_representations.clear(); + ecl::TimeStamp t; + t = time_1_3; t -= ecl::TimeStamp(5.1); + double_representations.push_back(t); + t = time_1_3; t -= ecl::TimeStamp(5.8); + double_representations.push_back(t); + t = time_1_3; t -= ecl::TimeStamp(1.5); + double_representations.push_back(t); + t = time_n_1_3; t -= ecl::TimeStamp(1.5); + double_representations.push_back(t); + t = time_n_1_3; t -= ecl::TimeStamp(-0.8); + double_representations.push_back(t); + t = time_n_1_3; t -= ecl::TimeStamp(-5.8); + double_representations.push_back(t); + if ( verbose ) { + std::cout << "Operator -=\n "; + for (const float& d : double_representations) { + std::cout << d << " "; + } + std::cout << std::endl; + } + EXPECT_FLOAT_EQ(-3.8, double_representations[0]); + EXPECT_FLOAT_EQ(-4.5, double_representations[1]); + EXPECT_FLOAT_EQ(-0.2, double_representations[2]); + EXPECT_FLOAT_EQ(-2.8, double_representations[3]); + EXPECT_FLOAT_EQ(-0.5, double_representations[4]); + EXPECT_FLOAT_EQ(4.5, double_representations[5]); + /**************************************** + ** Operator + + ****************************************/ + double_representations.clear(); timestamps.clear(); + double_representations.push_back(time_1_3 + time_n_2_3); timestamps.push_back(time_1_3 + time_n_2_3); + double_representations.push_back(time_1_3 + time_n_2_7); timestamps.push_back(time_1_3 + time_n_2_7); + double_representations.push_back(time_1_3 + time_n_1_7); timestamps.push_back(time_1_3 + time_n_1_7); + double_representations.push_back(time_0_3 + time_n_0_7); timestamps.push_back(time_0_3 + time_n_0_7); + double_representations.push_back(time_1_3 + time_n_0_7); timestamps.push_back(time_1_3 + time_n_0_7); + double_representations.push_back(time_2_3 + time_n_0_7); timestamps.push_back(time_2_3 + time_n_0_7); + double_representations.push_back(time_n_1_3 + time_n_1_7); timestamps.push_back(time_n_1_3 + time_n_1_7); + double_representations.push_back(time_n_1_7 + time_n_1_7); timestamps.push_back(time_n_1_7 + time_n_1_7); + if ( verbose ) { + std::cout << "Operator +" << std::endl; + std::cout << " 1.3 + (-2.3): " << double_representations[0] << std::endl; + std::cout << " 1.3 + (-2.7): " << double_representations[1] << std::endl; + std::cout << " 1.3 + (-1.7): " << double_representations[2] << std::endl; + std::cout << " 0.3 + (-0.7): " << double_representations[3] << std::endl; + std::cout << " 1.3 + (-0.7): " << double_representations[4] << std::endl; + std::cout << " 2.3 + (-0.7): " << double_representations[5] << std::endl; + std::cout << " -1.3 + (-1.7): " << double_representations[6] << std::endl; + std::cout << " -1.7 + (-1.7): " << double_representations[7] << std::endl; + } + EXPECT_FLOAT_EQ(-1.0, double_representations[0]); EXPECT_EQ(0, timestamps[0].nsec()); + EXPECT_FLOAT_EQ(-1.4, double_representations[1]); EXPECT_EQ(-400000000, timestamps[1].nsec()); + EXPECT_FLOAT_EQ(-0.4, double_representations[2]); EXPECT_EQ(-400000000, timestamps[2].nsec()); + EXPECT_FLOAT_EQ(-0.4, double_representations[3]); EXPECT_EQ(-400000000, timestamps[3].nsec()); + EXPECT_FLOAT_EQ(0.6, double_representations[4]); EXPECT_EQ(600000000, timestamps[4].nsec()); + EXPECT_FLOAT_EQ(1.6, double_representations[5]); EXPECT_EQ(600000000, timestamps[5].nsec()); + EXPECT_FLOAT_EQ(-3.0, double_representations[6]); EXPECT_EQ(000000000, timestamps[6].nsec()); + EXPECT_FLOAT_EQ(-3.4, double_representations[7]); EXPECT_EQ(-400000000, timestamps[7].nsec()); + + /**************************************** + ** Operator += + ****************************************/ + double_representations.clear(); timestamps.clear(); + t = time_1_3; t += time_n_2_3; + double_representations.push_back(t); timestamps.push_back(t); + t = time_1_3; t += time_n_2_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_1_3; t += time_n_1_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_0_3; t += time_n_0_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_1_3; t += time_n_0_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_2_3; t += time_n_0_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_n_1_3; t += time_n_1_7; + double_representations.push_back(t); timestamps.push_back(t); + t = time_n_1_7; t += time_n_1_7; + double_representations.push_back(t); timestamps.push_back(t); + if ( verbose ) { + std::cout << "Operator +=" << std::endl; + std::cout << " 1.3 + (-2.3): " << double_representations[0] << std::endl; + std::cout << " 1.3 + (-2.7): " << double_representations[1] << std::endl; + std::cout << " 1.3 + (-1.7): " << double_representations[2] << std::endl; + std::cout << " 0.3 + (-0.7): " << double_representations[3] << std::endl; + std::cout << " 1.3 + (-0.7): " << double_representations[4] << std::endl; + std::cout << " 2.3 + (-0.7): " << double_representations[5] << std::endl; + std::cout << " -1.3 + (-1.7): " << double_representations[6] << std::endl; + std::cout << " -1.7 + (-1.7): " << double_representations[7] << std::endl; + } + EXPECT_FLOAT_EQ(-1.0, double_representations[0]); EXPECT_EQ(0, timestamps[0].nsec()); + EXPECT_FLOAT_EQ(-1.4, double_representations[1]); EXPECT_EQ(-400000000, timestamps[1].nsec()); + EXPECT_FLOAT_EQ(-0.4, double_representations[2]); EXPECT_EQ(-400000000, timestamps[2].nsec()); + EXPECT_FLOAT_EQ(-0.4, double_representations[3]); EXPECT_EQ(-400000000, timestamps[3].nsec()); + EXPECT_FLOAT_EQ(0.6, double_representations[4]); EXPECT_EQ(600000000, timestamps[4].nsec()); + EXPECT_FLOAT_EQ(1.6, double_representations[5]); EXPECT_EQ(600000000, timestamps[5].nsec()); + EXPECT_FLOAT_EQ(-3.0, double_representations[6]); EXPECT_EQ(000000000, timestamps[6].nsec()); + EXPECT_FLOAT_EQ(-3.4, double_representations[7]); EXPECT_EQ(-400000000, timestamps[7].nsec()); + + /**************************************** + ** Operator < + ****************************************/ + std::vector comparisons; + comparisons.push_back(time_n_1_3 < time_n_2_3); + comparisons.push_back(time_n_1_3 < time_2_3); + comparisons.push_back(time_1_3 < time_n_2_3); + comparisons.push_back(time_1_3 < time_2_3); + comparisons.push_back(time_n_2_3 < time_n_1_3); + comparisons.push_back(time_n_2_3 < time_1_3); + comparisons.push_back(time_2_3 < time_n_1_3); + comparisons.push_back(time_2_3 < time_1_3); + comparisons.push_back(time_n_0_3 < time_n_0_7); + comparisons.push_back(time_n_0_3 < time_0_7); + comparisons.push_back(time_0_3 < time_n_0_7); + comparisons.push_back(time_0_3 < time_0_7); + comparisons.push_back(time_n_0_7 < time_n_0_3); + comparisons.push_back(time_n_0_7 < time_0_3); + comparisons.push_back(time_0_7 < time_n_0_3); + comparisons.push_back(time_0_7 < time_0_3); + if ( verbose ) { + std::cout << "Operator <" << std::endl; + std::cout << " -1.3 < -2.3: " << (comparisons[0] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -1.3 < 2.3: " << (comparisons[1] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 1.3 < -2.3: " << (comparisons[2] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 1.3 < 2.3: " << (comparisons[3] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -2.3 < -1.3: " << (comparisons[4] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -2.3 < 1.3: " << (comparisons[5] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 2.3 < -1.3: " << (comparisons[6] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 2.3 < 1.3: " << (comparisons[7] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -0.3 < -0.7: " << (comparisons[8] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -0.3 < 0.7: " << (comparisons[9] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 0.3 < -0.7: " << (comparisons[10] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 0.3 < 0.7: " << (comparisons[11] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -0.7 < -0.3: " << (comparisons[12] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " -0.7 < 0.3: " << (comparisons[13] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 0.7 < -0.3: " << (comparisons[14] ? std::string("true") : std::string("false")) << std::endl; + std::cout << " 0.7 < 0.3: " << (comparisons[15] ? std::string("true") : std::string("false")) << std::endl; + } + std::vector expected = { false, true, false, true, true, true, false, false, false, true, false, true, true, true, false, false }; + for ( unsigned int i = 0; i < expected.size(); ++i ) { + if ( expected[i] ) { + EXPECT_TRUE(comparisons[i]); + } else { + EXPECT_FALSE(comparisons[i]); + } + } + // TODO other comparison tests - didn't have to change that code for negative numbers +} + +#endif /* ECL_HAS_TIMESTAMP */ + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/.cproject b/ros2_ws/src/ecl_core/ecl_type_traits/.cproject new file mode 100644 index 0000000..55cd8e3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/.cproject @@ -0,0 +1,347 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + all + true + true + true + + + make + + clean + true + true + true + + + make + tests + true + true + true + + + make + test + true + true + true + + + make + + utilities + true + true + true + + + + diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/.project b/ros2_ws/src/ecl_core/ecl_type_traits/.project new file mode 100644 index 0000000..5eff9bc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/.project @@ -0,0 +1,79 @@ + + + ecl_type_traits + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_type_traits/CHANGELOG.rst new file mode 100644 index 0000000..106ed9b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/CHANGELOG.rst @@ -0,0 +1,12 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_type_traits +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +0.60.8 (2014-02-10) +------------------- + +0.60.7 (2014-02-03) +------------------- + +0.60.6 (2014-01-29) +------------------- diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/CMakeLists.txt new file mode 100644 index 0000000..40357e3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/CMakeLists.txt @@ -0,0 +1,50 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_type_traits) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_mpl REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################### +# Sources +############################################################################### + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################### +# Exports +############################################################################### + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_mpl +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..895b544 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(type_traits) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits.hpp b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits.hpp new file mode 100644 index 0000000..3e34b7d --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits.hpp @@ -0,0 +1,24 @@ +/** + * @file include/ecl/type_traits.hpp + * + * @brief Collects headers for ecl_type_traits. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TYPE_TRAITS_HPP_ +#define ECL_TYPE_TRAITS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "type_traits/macros.hpp" +#include "type_traits/traits.hpp" +#include "type_traits/fundamental_types.hpp" +#include "type_traits/numeric_limits.hpp" + +#endif /* ECL_TYPE_TRAITS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/CMakeLists.txt new file mode 100644 index 0000000..c735670 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/type_traits) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/fundamental_types.hpp b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/fundamental_types.hpp new file mode 100644 index 0000000..699960a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/fundamental_types.hpp @@ -0,0 +1,351 @@ +/** + * @file /ecl_type_traits/include/ecl/type_traits/fundamental_types.hpp + * + * @brief Trait types for fundamental types. + * + * @date 29/07/2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TYPE_TRAITS_FUNDAMENTAL_TYPES_HPP_ +#define ECL_TYPE_TRAITS_FUNDAMENTAL_TYPES_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Namespace +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Integers +*****************************************************************************/ +/** + * @brief Default action for detection of a fundamental integral type (false). + * + * Sets the default value (false) for detection of a fundamental integral type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_integral : public False {}; + + +/** + * @brief Integral trait for char types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for unsigned char types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for short types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for unsigned short types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for int types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for unsigned int types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for long types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for unsigned long types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for long long types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/** + * @brief Integral trait for unsigned long long types. + * + * Specialisation for the is_a_integral trait. + */ +template <> +class is_integral : public True {}; + +/***************************************************************************** +** Unsigned Integers +*****************************************************************************/ +/** + * @brief Default action for detection of an unsigned integral type (false). + * + * Sets the default value (false) for detection of an unsigned integral type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_unsigned : public False {}; + +/** + * @brief Unsigned trait for unsigned char types. + */ +template <> +class is_unsigned : public True {}; + +/** + * @brief Unsigned trait for unsigned short types. + */ +template <> +class is_unsigned : public True {}; + +/** + * @brief Unsigned trait for unsigned int types. + */ +template <> +class is_unsigned : public True {}; + +/** + * @brief Unsigned trait for unsigned long types. + */ +template <> +class is_unsigned : public True {}; + +/** + * @brief Unsigned trait for unsigned long long types. + */ +template <> +class is_unsigned : public True {}; + +/***************************************************************************** +** Signed Integers +*****************************************************************************/ +/** + * @brief Default action for detection of a signed integral type (false). + * + * Sets the default value (false) for detection of signed integral type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_signed : public False {}; + +/** + * @brief Unsigned trait for signed char types. + */ +template <> +class is_signed : public True {}; + +/** + * @brief Unsigned trait for signed short types. + */ +template <> +class is_signed : public True {}; + +/** + * @brief Unsigned trait for signed int types. + */ +template <> +class is_signed : public True {}; + +/** + * @brief Unsigned trait for signed long types. + */ +template <> +class is_signed : public True {}; + +/** + * @brief Unsigned trait for signed long long types. + */ +template <> +class is_signed : public True {}; + + +/***************************************************************************** +** Floats +*****************************************************************************/ + +/** + * @brief Default action for detection of a fundamental float type (false). + * + * Sets the default value (false) for detection of a fundamental float type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_float : public False {}; + +/** + * @brief Float trait for float types. + * + * Specialisation for the is a float trait for float types. + */ +template <> +class is_float : public True {}; + +/** + * @brief Float trait for double types. + * + * Specialisation for the is a float trait for double types. + */ +template <> +class is_float : public True {}; + +/** + * @brief Float trait for long double types. + * + * Specialisation for the is a float trait for double types. + */ +template <> +class is_float : public True {}; + +/***************************************************************************** +** Bytes +*****************************************************************************/ + +/** + * @brief Default action for detection of a fundamental signed byte type (false). + * + * Sets the default value (false) for detection of a fundamental signed byte type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_signed_byte : public False {}; + +/** + * @brief Signed byte trait for signed char types. + * + * Specialisation for the is a signed byte trait for signed char types. + */ +template <> +class is_signed_byte : public True {}; + +/** + * @brief Signed byte trait for char types if typedef'd to signed char. + * + * Specialisation for the is a signed byte trait for char types. This + * depends on whether the platform has typedef'd char to signed char + * or not. + */ +template <> +class is_signed_byte : public Bool::is_signed> {}; + +/** + * @brief Default action for detection of a fundamental unsigned byte type (false). + * + * Sets the default value (false) for detection of a fundamental unsigned byte type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_unsigned_byte : public False {}; + +/** + * @brief Unsigned byte trait for unsigned char types. + * + * Specialisation for the is a unsigned byte trait for unsigned char types. + */ +template <> +class is_unsigned_byte : public True {}; + +/** + * @brief Unsigned byte trait for char types if typedef'd to unsigned char. + * + * Specialisation for the is a unsigned byte trait for char types. This + * depends on whether the platform has typedef'd char to unsigned char + * or not. + */ +template <> +class is_unsigned_byte : public Bool::is_signed> {}; + +/** + * @brief Default action for detection of a fundamental byte type (false). + * + * Sets the default value (false) for detection of a fundamental byte type. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_byte : public False {}; + +/** + * @brief Byte trait for signed char types. + * + * Specialisation for the is a byte trait for signed char types. + */ +template <> +class is_byte : public True {}; + +/** + * @brief Byte trait for char types. + * + * Specialisation for the is a byte trait for char types. + */ +template <> +class is_byte : public True {}; + +/** + * @brief Byte trait for unsigned char types. + * + * Specialisation for the is a byte trait for unsigned char types. + */ +template <> +class is_byte : public True {}; + +} // namespace ecl + +#endif /* ECL_TYPE_TRAITS_FUNDAMENTAL_TYPES_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/macros.hpp b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/macros.hpp new file mode 100644 index 0000000..a88850e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/macros.hpp @@ -0,0 +1,40 @@ +/** + * @file /include/ecl/type_traits/macros.hpp + * + * @brief Macros for windows dlls. + * + * @date March 2013. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TYPE_TRAITS_MACROS_HPP_ +#define ECL_TYPE_TRAITS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** PreProcessing +*****************************************************************************/ +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_type_traits_EXPORTS // we are building a shared lib/dll + #define ecl_type_traits_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_type_traits_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_type_traits_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_type_traits_PUBLIC + #define ecl_type_traits_LOCAL +#endif + + +#endif /* ECL_TYPE_TRAITS_MACROS_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/numeric_limits.hpp b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/numeric_limits.hpp new file mode 100644 index 0000000..0fa07f7 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/numeric_limits.hpp @@ -0,0 +1,303 @@ +/** + * @file /ecl_type_traits/include/ecl/type_traits/numeric_limits.hpp + * + * @brief Expand on the std numeric limits classes. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TYPE_TRAITS_NUMERIC_LIMITS_HPP_ +#define ECL_TYPE_TRAITS_NUMERIC_LIMITS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Parent Template +*****************************************************************************/ +/** + * @brief Expands the std numeric_limits class. + * + * This (the non-specialized template) simply returns the same + * functionality (via inheritance) as the std::numeric_limits class. + * + * - http://www.cplusplus.com/reference/std/limits/numeric_limits/ + * + * Specialisations of this class expand its definitions. + * + * Note that since this class and all its specialisations inherit + * the std::numeric_limits class, it + * is only really usable for fundamental c++ types. To extend + * non-fundamental types however, it is perfectly ok to specialise + * and add your own numeric_limits functionality. + * + * Also note that once the future c++0x standard is in, support + * in std::numeric_limits will be better and we can do away with much + * of the implementation in the derived classes here. + * + * @tparam T : the type to check (currently must be a fundamental type). + */ +template +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + numeric_limits() {} +private: +}; + +/***************************************************************************** +** Specialisations +*****************************************************************************/ +/** + * @brief Expands the std numeric_limits class for char. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const char one = 1; + static const uint16 bits = ECL_SIZE_OF_CHAR*8; + static const uint16 bytes = ECL_SIZE_OF_CHAR; + static const char minimum = CHAR_MIN; + static const char maximum = CHAR_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for unsigned char. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const unsigned char one = 1U; + static const uint16 bits = ECL_SIZE_OF_CHAR*8; + static const uint16 bytes = ECL_SIZE_OF_CHAR; + static const unsigned char minimum = 0U; + static const unsigned char maximum = UCHAR_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for short. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const short one = 1; + static const uint16 bits = ECL_SIZE_OF_SHORT*8; + static const uint16 bytes = ECL_SIZE_OF_SHORT; + static const short minimum = SHRT_MIN; + static const short maximum = SHRT_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for unsigned short. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const unsigned short one = 1U; + static const uint16 bits = ECL_SIZE_OF_SHORT*8; + static const uint16 bytes = ECL_SIZE_OF_SHORT; + static const unsigned short minimum = 0U; + static const unsigned short maximum = USHRT_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for int. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const int one = 1; + static const uint16 bits = ECL_SIZE_OF_INT*8; + static const uint16 bytes = ECL_SIZE_OF_INT; + static const int minimum = INT_MIN; + static const int maximum = INT_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for unsigned int. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const unsigned int one = 1U; + static const uint16 bits = ECL_SIZE_OF_INT*8; + static const uint16 bytes = ECL_SIZE_OF_INT; + static const unsigned int minimum = 0U; + static const unsigned int maximum = UINT_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + + +/** + * @brief Expands the std numeric_limits class for long. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const long one = 1L; + static const uint16 bits = ECL_SIZE_OF_LONG*8; + static const uint16 bytes = ECL_SIZE_OF_LONG; + static const long minimum = LONG_MIN; + static const long maximum = LONG_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for unsigned long. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const unsigned long one = 1UL; + static const uint16 bits = ECL_SIZE_OF_LONG*8; + static const uint16 bytes = ECL_SIZE_OF_LONG; + static const unsigned long minimum = 0UL; + static const unsigned long maximum = ULONG_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for long long. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const long long one = 1LL; + static const uint16 bits = ECL_SIZE_OF_LONG_LONG*8; + static const uint16 bytes = ECL_SIZE_OF_LONG_LONG; + static const long long minimum = LLONG_MIN; + static const long long maximum = LLONG_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for unsigned long long. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const unsigned long long one = 1ULL; + static const uint16 bits = ECL_SIZE_OF_LONG_LONG*8; + static const uint16 bytes = ECL_SIZE_OF_LONG_LONG; + static const unsigned long long minimum = 0ULL; + static const unsigned long long maximum = ULLONG_MAX; + + typedef float Precision; + static const Precision dummy_precision; +}; + +/** + * @brief Expands the std numeric_limits class for float. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const uint16 bits = ECL_SIZE_OF_FLOAT*8; + static const uint16 bytes = ECL_SIZE_OF_FLOAT; + + typedef float Precision; /**< @brief Type used to specify precisions. **/ + static const float dummy_precision; /**< @brief Default precision. **/ + + static const float minimum; + static const float maximum; +}; + +/** + * @brief Expands the std numeric_limits class for float. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const uint16 bits = ECL_SIZE_OF_DOUBLE*8; + static const uint16 bytes = ECL_SIZE_OF_DOUBLE; + + typedef double Precision; /**< @brief Type used to specify precisions. **/ + static const double dummy_precision; /**< @brief Default precision. **/ + + static const double minimum; + static const double maximum; +}; + +/** + * @brief Expands the std numeric_limits class for float. + * + * @sa ecl::numeric_limits + */ +template <> +class ecl_type_traits_PUBLIC numeric_limits : public std::numeric_limits { +public: + static const uint16 bits = ECL_SIZE_OF_LONG_DOUBLE*8; + static const uint16 bytes = ECL_SIZE_OF_LONG_DOUBLE; + + typedef long double Precision; /**< @brief Type used to specify precisions. **/ + static const long double dummy_precision; /**< @brief Default precision. **/ + + static const long double minimum; + static const long double maximum; +}; + + +} // namespace ecl + +#endif /* ECL_TYPE_TRAITS_NUMERIC_LIMITS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/traits.hpp b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/traits.hpp new file mode 100644 index 0000000..e3de8fc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/include/ecl/type_traits/traits.hpp @@ -0,0 +1,34 @@ +/** + * @file /ecl_type_traits/include/ecl/type_traits/traits.hpp + * + * @brief Forward declaration for a general purpose traits class. + * + * @date September, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TYPE_TRAITS_TRAITS_HPP_ +#define ECL_TYPE_TRAITS_TRAITS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Forward declaration for a general purpose traits mechanims. + * + * Specialise this to define traits for your particular class. + */ +template struct ecl_traits; + +} // namespace ecl + +#endif /* ECL_TYPE_TRAITS_TRAITS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/mainpage.dox b/ros2_ws/src/ecl_core/ecl_type_traits/mainpage.dox new file mode 100644 index 0000000..88ad587 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/mainpage.dox @@ -0,0 +1,101 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Provides some cross platform type traits above and beyond what is provided + by c++. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The error interfaces + using ecl::numeric_limits; + using ecl::is_integral; + using ecl::is_float; + using ecl::is_signed; + using ecl::is_unsigned; + using ecl::is_byte; + @endcode + + You will also need to link to -lecl_type_traits. + +\section usage Usage + +\subsection numericLimits Numeric Limits + + This extends c++'s numeric_limits class for fundamental types, providing in addition, static constants + that can be utilised as template arguments (as opposed to c macros or c++ functions in numeric_limits). + For integral types, an example of the extras available: + + @code + ecl::uint16 bits = NumericLimits::bits; + ecl::uint16 bytes = NumericLimits::bytes; + int j = NumericLimits::one; + int i = NumericLimits::minimum; + int k = NumericLimits::maximum; + @endcode + + An example of some extras for a float type: + + @code + ecl::uint16 bits = NumericLimits::bits; + ecl::uint16 bytes = NumericLimits::bytes; + + // precision setting is a rough, but useful aid to bounding the accuracy for some math calculations + NumericLimits::Precision p = NumericLimits::dummy_precision(); + + // note, numeric_limits::min() is the smallest + // positive value, this is the smallest negative value. + float minimum = NumericLimits::minimum; + float maximum = NumericLimits::maximum; + @endcode + + + Note that it inherits the numeric_limits class, so all the functions therein can also be used. + +\subsection isA Fundamental Type Traits + + These are in the upcoming C++0x standard, so are only a temporary feature in the ecl. They + are a subset and work just like boosts type traits. More will be added as needed. The + code snippet below is for runtime code, but they're actually more useful with enable_if + in determining which compile time template specialisations to instantiate. + + + @code + if ( is_float::value ) { + // take some action + } + @endcode + + The current list of type traits include: + + - @ref ecl::is_integral "is_integral" + - @ref ecl::is_signed "is_signed" + - @ref ecl::is_unsigned "is_unsigned" + - @ref ecl::is_float "is_float" + - @ref ecl::is_byte "is_byte" + - @ref ecl::is_signed_byte "is_signed_byte" + - @ref ecl::is_unsigned_byte "is_unsigned_byte" + +\section unitTests Unit Tests + + - src/test/numeric_limits.cpp + - src/test/fundamental_types.cpp + +\section ChangeLog + + - Mar 11 : added the is_xxx_byte type traits. + - Feb 11 : collected type traits from ecl_config and ecl_mpl. + - Sep 10 : @ref ecl::is_byte "is_byte" trait for detection of single byte types added. + - Aug 10 : @ref ecl::is_signed "is_signed", @ref ecl::is_unsigned "is_unsigned" trait types added. + - Jul 10 : @ref ecl::is_integral "is_integral", @ref ecl::is_float "is_float" trait types added. + + +*/ \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/package.xml b/ros2_ws/src/ecl_core/ecl_type_traits/package.xml new file mode 100644 index 0000000..45f6631 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/package.xml @@ -0,0 +1,35 @@ + + + ecl_type_traits + 1.2.1 + + Extends c++ type traits and implements a few more to boot. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_type_traits + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_mpl + + ecl_license + ecl_mpl + ecl_config + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/src/CMakeLists.txt new file mode 100644 index 0000000..cc8fa8e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(lib) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() + +add_subdirectory(utils) + diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/CMakeLists.txt new file mode 100644 index 0000000..0f55b9a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/CMakeLists.txt @@ -0,0 +1,36 @@ +############################################################################## +# Sources +############################################################################## + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +target_link_libraries(${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_mpl::ecl_mpl +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/numeric_limits.cpp b/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/numeric_limits.cpp new file mode 100644 index 0000000..a65d9a9 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/lib/numeric_limits.cpp @@ -0,0 +1,108 @@ +/** + * @file /ecl_type_traits/src/lib/numeric_limits.cpp + * + * @brief Implementation of the extended numeric limit specialisations. + * + * @date February 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/type_traits/numeric_limits.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Static Variables +*****************************************************************************/ +/** + * @cond DO_NOT_DOXYGEN + */ + +const char numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const char numeric_limits::minimum; +const char numeric_limits::maximum; + +const unsigned char numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const unsigned char numeric_limits::minimum; +const unsigned char numeric_limits::maximum; + + +const int16 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const int16 numeric_limits::minimum; +const int16 numeric_limits::maximum; + +const uint16 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const uint16 numeric_limits::minimum; +const uint16 numeric_limits::maximum; + +const int32 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const int32 numeric_limits::minimum; +const int32 numeric_limits::maximum; + +const uint32 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const uint32 numeric_limits::minimum; +const uint32 numeric_limits::maximum; + +const int64 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const int64 numeric_limits::minimum; +const int64 numeric_limits::maximum; + +const uint64 numeric_limits::one; +const uint16 numeric_limits::bits; +const uint16 numeric_limits::bytes; +const uint64 numeric_limits::minimum; +const uint64 numeric_limits::maximum; + +/* Dummy precision is a useful concept borrowed from eigen. It is used to help define + * fuzzy operators which is especially handy for comparing floats which are notorious with + * a strict '=' operator. + * + * @sa eigen/include/ecl/Eigen3/src/Core/NumTraits.h + */ +const numeric_limits::Precision numeric_limits::dummy_precision = 1e-5f; +const numeric_limits::Precision numeric_limits::dummy_precision = 1e-5f; +const numeric_limits::Precision numeric_limits::dummy_precision = 1e-5f; +const numeric_limits::Precision numeric_limits::dummy_precision = 1e-5f; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; +const numeric_limits::Precision numeric_limits::dummy_precision = 0.0; + +const float numeric_limits::minimum = -std::numeric_limits::max(); +const float numeric_limits::maximum = std::numeric_limits::max(); +const float numeric_limits::dummy_precision = 1e-5f; + +const double numeric_limits::minimum = -std::numeric_limits::max(); +const double numeric_limits::maximum = std::numeric_limits::max(); +const double numeric_limits::dummy_precision = 1e-12; + +const long double numeric_limits::minimum = -std::numeric_limits::max(); +const long double numeric_limits::maximum = std::numeric_limits::max(); +const long double numeric_limits::dummy_precision = 1e-15; +/** + * @endcond + */ +} // namespace ecl diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/CMakeLists.txt new file mode 100644 index 0000000..05a64d5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/CMakeLists.txt @@ -0,0 +1,18 @@ +############################################################################### +# Test Macro +############################################################################### + +macro(ecl_type_traits_add_gtest test_name) + ament_add_gtest(test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET test_${test_name}) + target_link_libraries(test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################## +# Files +############################################################################## + +ecl_type_traits_add_gtest(numeric_limits) +ecl_type_traits_add_gtest(fundamental_types) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/test/fundamental_types.cpp b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/fundamental_types.cpp new file mode 100644 index 0000000..e9e946f --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/fundamental_types.cpp @@ -0,0 +1,120 @@ +/** + * @file /ecl_type_traits/src/test/fundamental_types.cpp + * + * @brief Unit tests for fundamental_type traits. + * + * @date July 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/type_traits/fundamental_types.hpp" + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::is_integral; +using ecl::is_float; +using ecl::is_byte; +using ecl::is_signed_byte; +using ecl::is_unsigned_byte; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(TypeTraitTests,is_integral) { + bool result; + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(true, result); + result = is_integral::value; + EXPECT_EQ(false, result); + result = is_integral::value; + EXPECT_EQ(false, result); +} + +TEST(TypeTraitTests,is_float) { + bool result; + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(false, result); + result = is_float::value; + EXPECT_EQ(true, result); + result = is_float::value; + EXPECT_EQ(true, result); +} + +TEST(TypeTraitTests,is_byte) { + bool result; + + result = is_byte::value; + EXPECT_EQ(true, result); + result = is_byte::value; + EXPECT_EQ(true, result); + result = is_byte::value; + EXPECT_EQ(true, result); + + result = is_signed_byte::value; + if ( std::numeric_limits::is_signed ) { + EXPECT_EQ(true, result); + } else { + EXPECT_EQ(false, result); + } + result = is_signed_byte::value; + EXPECT_EQ(true, result); + result = is_signed_byte::value; + EXPECT_EQ(false, result); + + result = is_unsigned_byte::value; + if ( std::numeric_limits::is_signed ) { + EXPECT_EQ(false, result); + } else { + EXPECT_EQ(true, result); + } + result = is_unsigned_byte::value; + EXPECT_EQ(false, result); + result = is_unsigned_byte::value; + EXPECT_EQ(true, result); +} +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/test/numeric_limits.cpp b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/numeric_limits.cpp new file mode 100644 index 0000000..0c36852 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/test/numeric_limits.cpp @@ -0,0 +1,35 @@ +/** + * @file /ecl_type_traits/src/test/numeric_limits.cpp + * + * @brief Unit test for the expanded numeric limits. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "../../include/ecl/type_traits/numeric_limits.hpp" + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + + std::cout << "Sizeof Float: " << __SIZEOF_FLOAT__ << std::endl; + std::cout << "Sizeof Double: " << __SIZEOF_DOUBLE__ << std::endl; + std::cout << "Sizeof Long Double: " << __SIZEOF_LONG_DOUBLE__ << std::endl; + int i = 1 + ecl::numeric_limits::one; + std::cout << i << std::endl; + i = 1 + ecl::numeric_limits::one; + std::cout << i << std::endl; + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/CMakeLists.txt new file mode 100644 index 0000000..005da4e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################## +# Files +############################################################################## + +add_executable(ecl_detect_sizes detect_sizes.cpp) +set_target_properties(ecl_detect_sizes + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin +) +target_link_libraries(ecl_detect_sizes ${PROJECT_NAME}) +install(TARGETS ecl_detect_sizes RUNTIME DESTINATION bin) diff --git a/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/detect_sizes.cpp b/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/detect_sizes.cpp new file mode 100644 index 0000000..e503f8e --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_type_traits/src/utils/detect_sizes.cpp @@ -0,0 +1,157 @@ +/** + * @file /src/utils/detect_sizes.cpp + * + * @brief Sends a stream of data regarding math type sizes to stdout. + * + * @date April 2010 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include + +/***************************************************************************** +** using +*****************************************************************************/ + +using ecl::int8; +using ecl::uint8; +using ecl::int16; +using ecl::uint16; +using ecl::int32; +using ecl::uint32; +using ecl::int64; +using ecl::uint64; +using ecl::numeric_limits; + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " numeric_limits<>" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << static_cast(numeric_limits::minimum) << std::endl; + std::cout << "numeric_limits::max " << static_cast(numeric_limits::maximum) << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << static_cast(numeric_limits::minimum) << std::endl; + std::cout << "numeric_limits::max " << static_cast(numeric_limits::maximum) << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + std::cout << std::endl; + + std::cout << "numeric_limits::bytes " << numeric_limits::bytes << std::endl; + std::cout << "numeric_limits::bits " << numeric_limits::bits << std::endl; + std::cout << "numeric_limits::min " << numeric_limits::minimum << std::endl; + std::cout << "numeric_limits::max " << numeric_limits::maximum << std::endl; + +// std::cout << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << " Integer<>" << std::endl; +// std::cout << "***********************************************************" << std::endl; +// std::cout << std::endl; +// +// Integer<8>::type int_8 = 0x03; +// Integer<8>::utype uint_8 = 0x03; +// std::cout << "Integer<8>::type: " << int_8 << std::endl; +// std::cout << "Integer<8>::utype: " << uint_8 << std::endl; +// std::cout << "Integer<8>::min " << static_cast(Integer<8>::min) << std::endl; +// std::cout << "Integer<8>::one " << static_cast(Integer<8>::one) << std::endl; +// std::cout << "Integer<8>::max " << static_cast(Integer<8>::max) << std::endl; +// std::cout << "Integer<8>::umin " << static_cast(Integer<8>::umin) << std::endl; +// std::cout << "Integer<8>::uone " << static_cast(Integer<8>::uone) << std::endl; +// std::cout << "Integer<8>::umax " << static_cast(Integer<8>::umax) << std::endl; +// std::cout << std::endl; +// +// Integer<16>::type int_16 = 0x03; +// Integer<16>::utype uint_16 = 0x03; +// std::cout << "Integer<16>::type: " << int_16 << std::endl; +// std::cout << "Integer<16>::utype: " << uint_16 << std::endl; +// std::cout << "Integer<16>::min " << Integer<16>::min << std::endl; +// std::cout << "Integer<16>::one " << Integer<16>::one << std::endl; +// std::cout << "Integer<16>::max " << Integer<16>::max << std::endl; // This doesn't output the correct value. +// std::cout << "Integer<16>::umin " << Integer<16>::umin << std::endl; +// std::cout << "Integer<16>::uone " << Integer<16>::uone << std::endl; +// std::cout << "Integer<16>::umax " << Integer<16>::umax << std::endl; +// std::cout << std::endl; +// +// Integer<32>::type int_32 = 0x03; +// Integer<32>::utype uint_32 = 0x03; +// std::cout << "Integer<32>::type: " << int_32 << std::endl; +// std::cout << "Integer<32>::utype: " << uint_32 << std::endl; +// std::cout << "Integer<32>::min " << Integer<32>::min << std::endl; +// std::cout << "Integer<32>::one " << Integer<32>::one << std::endl; +// std::cout << "Integer<32>::max " << Integer<32>::max << std::endl; // This doesn't output the correct value. +// std::cout << "Integer<32>::umin " << Integer<32>::umin << std::endl; +// std::cout << "Integer<32>::uone " << Integer<32>::uone << std::endl; +// std::cout << "Integer<32>::umax " << Integer<32>::umax << std::endl; +// std::cout << std::endl; +// +// Integer<64>::type int_64 = 0x03; +// Integer<64>::utype uint_64 = 0x03; +// std::cout << "Integer<64>::type: " << int_64 << std::endl; +// std::cout << "Integer<64>::utype: " << uint_64 << std::endl; +// std::cout << "Integer<64>::min " << Integer<64>::min << std::endl; +// std::cout << "Integer<64>::one " << Integer<64>::one << std::endl; +// std::cout << "Integer<64>::max " << Integer<64>::max << std::endl; // This doesn't output the correct value. +// std::cout << "Integer<64>::umin " << Integer<64>::umin << std::endl; +// std::cout << "Integer<64>::uone " << Integer<64>::uone << std::endl; +// std::cout << "Integer<64>::umax " << Integer<64>::umax << std::endl; +// std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_core/ecl_utilities/.cproject b/ros2_ws/src/ecl_core/ecl_utilities/.cproject new file mode 100644 index 0000000..1ba77ce --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/.cproject @@ -0,0 +1,684 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + tests + + true + + true + + true + + + + + + make + + test + + true + + true + + true + + + + + + make + + clean + + true + + true + + true + + + + + + make + + -j8 + + install + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/.project b/ros2_ws/src/ecl_core/ecl_utilities/.project new file mode 100644 index 0000000..503bc00 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/.project @@ -0,0 +1,78 @@ + + + ecl_utilities + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + tests + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/CHANGELOG.rst b/ros2_ws/src/ecl_core/ecl_utilities/CHANGELOG.rst new file mode 100644 index 0000000..ab29b9a --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/CHANGELOG.rst @@ -0,0 +1,8 @@ +^^^^^^^^^ +Changelog +^^^^^^^^^ + +0.61.0 (2014-09-12) +------------------- +* partially bound binary function members. + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/CMakeLists.txt new file mode 100644 index 0000000..17ede64 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/CMakeLists.txt @@ -0,0 +1,75 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_utilities) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_concepts REQUIRED) +find_package(ecl_mpl REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_link_libraries( + ${PROJECT_NAME} + INTERFACE + ecl_concepts::ecl_concepts + ecl_mpl::ecl_mpl +) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_concepts + ecl_mpl +) +ament_package() diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/changelog.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/changelog.dox new file mode 100644 index 0000000..2e182b1 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/changelog.dox @@ -0,0 +1,28 @@ +/** +@page changelog ChangeLog + + +@section Changes + + - Feb 11 : Converters moved out to their own package. + - Mar 10 : Converters added a human readable hex string to byte array converter. + - Jul 09 : A @ref referencesGuide "const reference wrapper" wrapper generator (cref). + - Jul 09 : A @ref referencesGuide "reference wrapper" generator (ref). + - Jul 09 : A traits test for @ref referencesGuide "reference wrappers". + - Jul 09 : The @ref referencesGuide "reference wrapper" class. + - Jul 09 : @ref functionobjectsGuide "Function objects" revised to handle sigslots. + - Jun 09 : A simple set of @ref functionobjectsGuide "function objects" to handle function loading in higher level classes. + - May 09 : Converters for to character strings added and performance checked. + - May 09 : Converters for to character strings added and performance checked. + - Apr 09 : Converter structure and some simple converters added. + - Apr 09 : Converter structure and some simple converters added. + - Apr 09 : @ref parametersGuide "Parameters", a c++ templatised/convenient replacement for the verbose get/set methods added. + - Apr 09 : Design pattern for @ref singletonsGuide "singletons". + +@section Bugs + + - May 09 : Constructor args automatic type conversions were mistakenly grabbed by the templatised blueprint constructor - fixed. + - May 09 : Float and double conversions to character strings were slow - defaulted back to a sprintf implementation. + - Apr 09 : Fixed the get/set method accessors so that control of the internal variable is never lost by the parameter class. +**/ + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/flags.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/flags.dox new file mode 100644 index 0000000..4cdb9aa --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/flags.dox @@ -0,0 +1,114 @@ +/** + * @page flagsDocumentation Guides: Flags + * + * @section introduction What are they? + * + * Flags provide a type-safe way of storing OR-combinations of enum values. + * Flags is a template class, where Enum is an user defined enum type + * that holds a list of the appropriate flag values. + * + * The traditional C++ approach for storing OR-combinations of enum values is to + * use an int or uint variable. The inconvenience with this approach is that there's + * no type checking at all; any enum value can be OR'd with any other enum value + * and passed on to a function that takes an int. + * + * The technique here I found in the Qt library. It provides type safe checking of + * enum arguments (you cannot mix enum definitions arbitrarily without causing a + * compiler error). Usually the flags + * are independant - you can have any combination of the enum values + * currently configured. However with some masking tricks (see QLabel's + * setAlignment method) it is possible to group subsets of the enum so that only + * one flag from each subset can be triggered at any one point in time. + * + * @section Usage + * + * @subsection CompilingLinking Compiling & Linking + * + * Include the following at the top of any translation unit that requires + * compilation of signals and/or slots. + * @code + * #include + * + * using YCL::Utilities::Flags; + * @endcode + * + * @subsection Enum Enum Declaration + * + * Some care must be taken when defining the enum for use with this Flags class. + * The enum must classify each argument as an independant bit. For example, + * @code + * enum Setting + * { + * Fast 0x0001, + * Slow 0x0002, + * Red 0x0010, + * Blue 0x0020 + * }; + * @endcode + * Alternatively, the shift operator can also be used. + * + * @subsection Flag Flag Declaration + * + * It is easiest to declare the enum with a name corresponding to + * the type of flag it represents and then pluralise this with a convenient typedef + * when declaring the Flags class associated with it. For example, + * + * @code + * enum Setting + * { + * ... as above .... + * }; + * + * typedef Flags Settings; + * @endcode + * + * @subsection Helper functions + * + * There immediately exists a helper function that allows you to pipe further flags to the current + * flag container. + * @code + * settings = settings|Fast|Slow; + * @endcode + * A further convenience can be had if a simple friend piping operator is written alongside the + * definition of your enum: + * @code + * Flags operator|(Setting flagOne, Setting flagTwo) { return Flags(flagOne) | flagTwo; } + * @endcode + * This then enables you to configure flags very simply with: + * Thanks to the helper (friend) functions, it is very simple to initialise a Flags variable. + * @code + * Settings settings(Fast|Slow) + * settings = Fast|Slow; + * @endcode + + * Note, it would be convenient if a very general template such as the piping operator above could be included with the + * library. To date however, the only method I know of is to define a very general template operator function. + * This actually works with g++, however msvc9 does not like it, and its probably for good reason. Such a template + * operator in the global namespace will inevitably clash with other friend operators and result in ambiguities. + * + * @subsection Illegal Combinations + * + * Combinations can be made illegal through customised accessors. + * @code + * class A + * { + * public: + * void configure(Settings s) + * { + * if ( ( s.testFlag(Gold) && s_.testFlag(Dark) ) || + * ( s_.testFlag(Gold) && s.testFlag(Dark) ) || + * ( s.testFlag(Gold) && s.testFlag(Dark) ) ) + * { + * cout << "This combination is not permitted." << endl; + * return; + * } else { + * s_ = s; + * } + * } + * Settings settings() { return s_; } + + * private: + * Settings s_; + * }; + * @endcode + **/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/function_objects.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/function_objects.dox new file mode 100644 index 0000000..9b4a9a6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/function_objects.dox @@ -0,0 +1,153 @@ +/** + * @page functionobjectsGuide Guide: Function Objects + + @section Introduction + + Resolving c++ function passing (as arguments to other functions) + is complicated by the differences between global/static and member + functions as well as by the awkward syntax. Here we attempt to + provide a standardised approach to using them. + + @subsection Definition + + One way of standardising the approach is to utilise the idea of a + function object (also known as functor). A function object is simply + an object that characterises a function. In c++, this has three + advantages: + + - Function code can be inlined (instead of repeated pointer calls) when used repetitively in a loop. + - The function object can maintain state, something which pure function callbacks cannot do. + - The syntax is much cleaner and more flexible. + + An example of a unary function object is given below: + + @code + class Sum { + int val; + public: + Sum(int i) :val(i) { } + int operator()(int i) { return val+=i; } // unary function + }; + @endcode + + We also make a terminology distinction here when distinguishing between free and member + functions. Free functions are defined to be global or static functions. + + @section CompilingLinking Compiling & Linking + + Include some or all of the following at the top of any translation unit that requires + compilation of class that uses parameters. + @code + #include + + // The classes + using ecl::NullaryFunction; + using ecl::UnaryFunction; + using ecl::BinaryFunction; + using ecl::NullaryFreeFunction; + using ecl::UnaryFreeFunction; + using ecl::BoundUnaryFreeFunction; + using ecl::NullaryMemberFunction; + using ecl::BoundNullaryMemberFunction; + using ecl::UnaryMemberFunction; + using ecl::PartiallyBoundUnaryMemberFunction; + using ecl::BoundUnaryMemberFunction; + using ecl::NullaryFunctionCopy; + using ecl::NullaryFunctionReference; + using ecl::UnaryFunctionCopy; + using ecl::UnaryFunctionReference; + + // Overloaded utility functions + using ecl::generateFunctionObject; + @endcode + + Since it is a template class, no linking is required if you are only using this class. + + @section Usage + + Many of the higher level classes in the ecl utilise function objects, e.g. threads, signals and + slots. These classes expect certain concepts to be fulfilled when accepting + function objects as arguments and also make use of some of the convenience classes/tools in the above list. + + @subsection Concepts + + Classes that accept function objects generally utilise a template parameter and require the + function object to fulfill the requirements of a concept. For example, threads require + function objects to satisfy the nullary function concept. The current list of concepts for + function objects include: + + - NullaryFunction + + Documentation for the concepts can be found in the ecl_concepts package. + + @subsection manualconsSection Creating Your Own Function Objects + + When constructing your own function object classes to be used with higher level ecl components, they + must conform to the requirements of their target concept. For example, a suitable thread class + function object: + + @code + class ThreadFunction { + public: + typedef void result_type; + void operator()() { + // thread worker function + } + }; + ThreadFunction thread_function; + Thread thread(thread_function); // Alternatively Thread thread = Thread(ThreadFunction()); + @endcode + + @subsection wrappersSection Wrapping Free/Member Functions + + Wrapping functions can be done via construction calls to many of the classes listed above, however + to make it easier, there is the overloaded + @ref ecl::generateFunctionObject "generateFunctionObject" method. + + A good example of its usage is with the ecl Thread class where a + nullary function object is required for construction. + @code + int f(int i) {} + class A { + void f() {} + void g(int i) {} + }; + // ... + A a; + Thread thread0(generateFunctionObject(f, 3)); // Bind the first argument to a global function + Thread thread1(generateFunctionObject(&A::f, a)); // Bind an object instance with the nullary function + Thread thread2(generateFunctionObject(&A::g, a, 2)); // Bind object instance, first argument to a unary member function + @endcode + + For member functions, in the above code we bound the instance with the member function. Alternatively, you + can leave it free so that the following two lines of code produce the same result: + + @code + generateFunctionObject(&A::f, a)(); // This case produces and calls a nullary function + generateFunctionObject(&A::f)(a); // This case produces and calls a unary function + @endcode + + @subsection usageCase Case Scenario : Threads + + Threads uses the tools here, an example of thread function loading is shown below. + @code + A a; // Just an ordinary class with nullary member f(). + NullaryFunction function_object; // Conforms to the concept above. + Thread thread_f1(f); + Thread thread_f2(&A::f,a); + Thread thread_f3(generateFunctionObject(f)); + Thread thread_f4(generateFunctionObject(g,1)); + Thread thread_f5(generateFunctionObject(&A::f,a)); + Thread thread_f6(generateFunctionObject(&A::g,a,2)); + Thread thread_f7(function_object); + Thread thread_f8 = NullaryFunction(); + Thread thread_f8(ref(function_object)); + @endcode + + @section Limitations + + We only utilise at most one argument to any free/member function. In practice a limit has to be drawn somewhere + and I find you can always bundle however many arguments you wish into an appropriately defined structure, + so either none or one is always sufficient for all purposes. + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/mainpage.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/mainpage.dox new file mode 100644 index 0000000..d6aeb02 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/mainpage.dox @@ -0,0 +1,31 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section Package Summary + + This group includes various supporting tools and utilities useful for c++ programming. + + @section Guides + + - @ref functionobjectsGuide "Function Objects" - c++ object style function callbacks. + - @ref parametersGuide "Parameters" - a convenient parameter type for classes. + - @ref referencesGuide "Reference Wrappers" - wrappers for referenced objects. + - @ref singletonsGuide "Singletons" - unique, once off instantiations. + +@section unitTests Unit Tests + + - src/test/function_objects.cpp + - src/test/parameters.cpp + - src/test/references.cpp + - src/test/singleton.cpp + +@section Demos + + - src/examples/constructors.cpp : demos' the different ways of constructing an object. + +@section ChangeLog + + - @ref changelog "ChangeLog" + +*/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/namespaces.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/namespaces.dox new file mode 100644 index 0000000..42d8e06 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/namespaces.dox @@ -0,0 +1,8 @@ +/** + * @namespace ecl + * + * @brief Embedded control libraries. + * + * Various core libraries useful for embedded control systems. + **/ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/parameters.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/parameters.dox new file mode 100644 index 0000000..a199de8 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/parameters.dox @@ -0,0 +1,97 @@ +/** + * @page parametersGuide Guide: Parameters + + @section Introduction + + Parameter types substitute the basic types for a more convenient + templatised structure when used within a class. Ideally the only + way any member variable should be modified is via member functions + of the class itself. When you start allowing member variables to + be extracted and modified outside a class, you inevitably lose + control of the class (and in practice this happens by lazy/tired + programmers more often than not) and bugs start creeping in. + + The usual way to implement this is with get and set methods + providing access. However, this can get somewhat verbose for + simple classes: + + @code + class A { + public: + A() {}; + + int getCounter() const { return m_counter; } + void setCounter (const int& counter) { m_counter = counter; } + + private: + int m_counter; + }; + @endcode + + This can be simplified with the use of templates + and the () operator resulting in the Parameter class defined here. + + @section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that requires + compilation of class that uses parameters. + @code + #include + + using ecl::Parameter; + @endcode + + Since it is a template class, no linking is required if you are only using this class. + + @section Usage + + @subsection Parameters + + The parameter implementation of a class A (compare with the set/get implementation + described earlier) looks like: + + class A { + public: + A() {}; + + Parameter counter; + }; + @endcode + Here access to the variable is done very similarly (but without the + verbosity of set/get). + @code + + int main() { + A a; + a.counter(1); // <-- Sets the variable + cout << a.counter(); << endl; // <-- Gets the variable + } + @endcode + + Note that even though Parameter is defined publicly, the contents are + still privately allocated, but here they are tucked away in Parameter's internal + implementation. + + @subsection Convenience + + There are also convenience methods if the above usage is undesirable. + + @code + a.counter = 1; + int a_copy = a.counter; + @endcode + + The difference between these and public variables is that these can never be + set outside of the class. The reason - regualar public variables can be hooked by a + pointer/reference and then passed off to another function where the variable can be + modified...well outside of the control of the original class. In this case here, + the only hooks that can be made to the variable are const pointers or const + references. Thus, even though the notation is the same, these parameter variables + are protected by their constness. + + @section Examples + + - src/test/parameters.cpp + + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/references.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/references.dox new file mode 100644 index 0000000..acf87fe --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/references.dox @@ -0,0 +1,79 @@ +/** +@page referencesGuide Guide: Reference Wrappers + +@section Introduction + +There are situations where you may wish to overload a function with both non-referenced and +referenced arguments. Unfortunately, this is not directly possible with c++, it usually results +in an ambiguity. +@code +class A { +public: + template + void f(T i) { cout << "Not a reference input" << endl; } + + template + void f(T &i) { cout << "A reference input" << endl; } +} +@endcode + +One way to resolve this is to create a wrapper with a pointer to the object inside it (we call +this a reference wrapper) and pass it to the function as you would normally pass a copy. +Once accepted, the function can use some metaprogramming logic to determine the fate of the +accepted copy or reference wrapper. + +@section CompilingLinking Compiling & Linking + +Include the following at the top of any translation unit that uses +these container classes. +@code +#include + +using ecl::ReferenceWrapper +using ecl::ref +using ecl::cref +using ecl::addressOf +@endcode + +You will also need to link to -lecl_utilities. + +@section Usage + +@subsection ReferenceWrapper + +The easiest way to generate a reference wrapper is via the convenience functions ref/cref. For +example, below illustrates a referenced function object passed to a thread. + +@code +Thread thread(ref(function_object)); +@endcode + +The cref call creates a constant reference, useful when your api will only accept a constant. + +Accessing a reference wrapper is straight forward: + +@code +A a; +ReferenceWrapper wrapper = ref(a); + +A &a_ref = wrapper.reference(); +A *a_ptr = wrapper.pointer(); +@endcode +It can also be directly passed off as the type it wraps. + +@subsection Traits + +Testing for reference wrapper objects can be done via the is_reference_wrapper trait. + +@code +bool result = is_reference_wrapper::value +@endcode + +This is most useful when used as a template argument metafunction. + +@section Examples + +- src/test/references.cpp + + +**/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/doxygen/singletons.dox b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/singletons.dox new file mode 100644 index 0000000..3852056 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/doxygen/singletons.dox @@ -0,0 +1,61 @@ +/** + @page singletonsGuide Guide: Singletons + + @section Overview + + Singletons are a means of ensuring a single, unique copy of an + object can ever exist. There are various ways of implementing + singletons, the wikipedia + has a surprisingly good article on singletons and provides a snippet + that utilises the curiously recurring template pattern which is used as + the derivation for this form of the singleton. + + @section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that requires + compilation of a singleton derived class. + @code + #include + + using ecl::Singleton; + @endcode + + Since it is a template class, no linking is required if you are only using this class. + + @section Usage + + @subsection Inheriting + + This singleton is intended to be inherited by a deriving class - this saves + the work of actually reinventing the singleton mechanisms whenever you + wish to use a singleton. + + @code + class TestObject : public ecl::Singleton + { + friend class ecl::Singleton; + + public: + int value() { return data; } + + protected: + TestObject() : data(32) {} + + private: + int data; + }; + @endcode + + @subsection Calling + + If you use a macro as shown below, the instance can be conveniently and readably accessed, + + @code + #define Test TestObject::instance() + + ... + + cout << Test.value() << endl; + @endcode + + **/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..876d4b6 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(utilities) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities.hpp new file mode 100644 index 0000000..2d46620 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities.hpp @@ -0,0 +1,21 @@ +/** + * @file /include/ecl/utilities.hpp + * + * @brief Miscellaneous tools and utility functions. + * + * Miscellaneous tools and utility functions. + * + * @date April, 2009 + **/ +#ifndef ECL_UTILITIES_HPP_ +#define ECL_UTILITIES_HPP_ + +#include "utilities/blueprints.hpp" +#include "utilities/flags.hpp" +#include "utilities/function_objects.hpp" +#include "utilities/parameter.hpp" +#include "utilities/references.hpp" +#include "utilities/singleton.hpp" +#include "utilities/void.hpp" + +#endif /*ECL_UTILITIES_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/CMakeLists.txt new file mode 100644 index 0000000..e0c6047 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/CMakeLists.txt @@ -0,0 +1,8 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/utilities) + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/blueprints.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/blueprints.hpp new file mode 100644 index 0000000..f8d4a62 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/blueprints.hpp @@ -0,0 +1,117 @@ +/** + * @file /include/ecl/utilities/blueprints.hpp + * + * @brief Parent templates for blueprints and blueprint factories. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_UTILITIES_BLUEPRINT_FACTORY_HPP_ +#define ECL_UTILITIES_BLUEPRINT_FACTORY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief This is a parent template for blueprints using crtp. + * + * Blueprints of various sorts are often passed to a constructor of their + * associated class. If a template is used to in the constructor call, e.g. + * + * @code + * template + * A(const BluePrint& blueprint); + * @endcode + * + * then this tends to create function collisions with other template + * functions (especially streaming operators). To avoid this, we need + * a parent class, so for this we use the crtp style (because it avoids + * any virtual costs). + * + * Classes that are of type Derived must satisfy the blueprint concept + * (ecl::concepts::BluePrint). + */ +template +class BluePrint { +public: + /** + * @brief Blueprint concept checking. + * + * Check that the derived class satisfies the blueprint concept. + */ + BluePrint() { + ecl_compile_time_concept_check(BluePrintConcept); + } + /** + * @brief Use the blueprint to instantiate a new object. + * + * A crtp virtual call to its children's instantiate method. The template + * argument is used, because the crtp base cannot catch typedef's in its + * children at this point of the compilation. With the template parameter + * this check is delayed until enough of this base class is known. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @return BaseType : the type to be generated by the blueprint. + */ + template + BaseType implementInstantiate() { + return static_cast(this)->instantiate(); + } + /** + * @brief Apply the blueprint rules to an existing object. + * + * A crtp virtual call to its children's apply method. This acts on the + * blueprint's target class to configure it according to the blueprint. + * The template parameter is a trick to delay the determination of the + * target type, because at this point of the compilation it cannot + * retrieve the base_type from the derived type. + * + * Note, this cannot have the same name as the blueprint method because + * then the child will inherit it, even if it doesn't have the class and + * the concept check will fail. + * + * @param object : the object to be configured. + */ + template + void implementApply(BaseType& object) const { + static_cast(this)->apply(object); + } + + virtual ~BluePrint() {} +}; +/** + * @brief Primary template for blueprint factories. + * + * This is often used as a conveniently inheritable class for mixing in + * static blueprint methods within the class that is being generated. + * Mostly for use internally within the ecl. + */ +template +class BluePrintFactory { + private: + /** + * @brief Default constructor that locks this class from being used directly. + */ + BluePrintFactory() {}; + virtual ~BluePrintFactory() {}; +}; + +} // namespace ecl + + +#endif /* ECL_UTILITIES_BLUEPRINT_FACTORY_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/flags.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/flags.hpp new file mode 100644 index 0000000..19d44ae --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/flags.hpp @@ -0,0 +1,282 @@ +/** + * @file /ecl_utilities/include/ecl/utilities/flags.hpp + * + * Flags c++ style without all the bit operations. + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_UTILITIES_FLAGS_HPP_ +#define ECL_UTILITIES_FLAGS_HPP_ + +/***************************************************************************** + ** Includes + *****************************************************************************/ + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Classes + *****************************************************************************/ + +enum Bits +{ + Bit0 = 0x0000, Bit1 = 0x0001, Bit2 = 0x0002, Bit3 = 0x0004, Bit4 = 0x0008, Bit5 = 0x0010, Bit6 = 0x0020, + Bit7 = 0x0040, Bit8 = 0x0080, Bit9 = 0x0100, Bit10 = 0x0200, Bit11 = 0x0400, Bit12 = 0x0800, Bit13 = 0x1000, + Bit14 = 0x2000, Bit15 = 0x4000, Bit16 = 0x8000, +}; +/** + * @brief Convenience class for organising boolean flags. + * + * This class organises a group of flags (via enums) in a convenient + * and typesafe manner. It is essentially a container for flags (in the form + * of enums) with a convenient interface on top. + * + * Usage: + * + * - Define an appropriate bit-arithmetic enum. + * + * @code + * enum Settings { + * Fast 0x0001, + * Medium 0x0002, + * Slow 0x0004, + * Red 0x0010, + * Blue 0x0020 + * } + * @endcode + * + * - Pipe flags into the enum + * + * @code + * settings = settings|Fast|Slow; + * @endcode + * + * - Set up a friend operator on the enum type for more convenient piping (see the dox). + * - Use one of the variety of mask/compliment/access operators for handling (see method documentation). + **/ +template + class Flags + { + public: + /********************* + ** C&D + **********************/ + Flags() : value(0) {}; /**< Default constructor. **/ + Flags(const Flags & other) : value(other.value) {}; /**< Copy constructor. **/ + Flags(Enum flag) : value(flag) {}; /**< Raw constructor. **/ + ~Flags() { } + ; + + /********************* + ** Utility + **********************/ + void clear() { value = 0; } /**< Clear all flags. **/ + /** + * Test current status of a flag. + **/ + bool testFlag(Enum flag) const + { + if ((value & flag) != 0) + { + return true; + } + else + { + if ( ( flag == 0 ) && ( value == 0 ) ) { + return true; + } else { + return false; + } + } + } + ; + + /********************* + ** Type compatibility + **********************/ + operator int() const + { + return value; + } + ; /**< Type compatibility with ints. **/ + + /****************************************** + ** Return new instance + *******************************************/ + /** + * Mask operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator&(int mask) const + { + Flags f; + f.value = value & mask; + return f; + } + ; + /** + * Single flag masking operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator&(Enum flag) const + { + Flags f; + f.value = value & flag; + return f; + } + ; + /** + * OR operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator|(Flags other) const + { + Flags f; + f.value = value | other.value; + return f; + } + ; + /** + * Single flag OR operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator|(Enum flag) const + { + Flags f; + f.value = value | flag; + return f; + } + ; + /** + * XOR operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator^(Flags other) const + { + Flags f; + f.value = value ^ other.value; + return f; + } + ; + /** + * Single flag XOR operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator^(Enum flag) const + { + Flags f; + f.value = value ^ flag; + return f; + } + ; + /** + * Complement operator. + * @return Flags : new instance of the flag set. + **/ + Flags operator~() const + { + Flags f; + f.value = ~value; + return f; + } + ; + + /****************************************** + ** Update current instance + *******************************************/ + /** + * Assignment operator. + * @return Flags : updated instance of the flag set. + **/ + Flags & operator=(const Flags & other) + { + value = other.value; + return *this; + } + ; + /** + * Assignment operator. + * @return Flags : updated instance of the flag set. + **/ + Flags & operator=(const Enum & flag) + { + value = static_cast(flag); + return *this; + } + ; + /** + * Self operating mask. + * @return Flags : updated instance of the masked flag set. + **/ + Flags & operator&=(int mask) + { + value &= mask; + return *this; + } + ; + /** + * Self operating OR operation. + * @return Flags : updated instance of the masked flag set. + **/ + Flags & operator|=(Flags other) + { + value |= other; + return *this; + } + ; + /** + * Self operating OR operation with a single flag. + * @return Flags : updated instance of the masked flag set. + **/ + Flags & operator|=(Enum flag) + { + value |= flag; + return *this; + } + ; + /** + * Self operating XOR operation. + * @return Flags : updated instance of the masked flag set. + **/ + Flags & operator^=(Flags other) + { + value ^= other; + return *this; + } + ; + /** + * Self operating XOR operation with a single flag. + * @return Flags : updated instance of the masked flag set. + **/ + Flags & operator^=(Enum flag) + { + value ^= flag; + return *this; + } + ; + + /********************* + ** Helper Methods + **********************/ + /** + * Adding a flag (OR operation) to an existing flag set. + * @return Flags : resulting instance of the flag combination. + **/ + friend inline Flags operator|(Enum flag, Flags flags) + { + return flags | flag; + } + private: + int value; + }; + +} // namespace ecl + +#endif /* ECL_UTILITIES_FLAGS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/function_objects.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/function_objects.hpp new file mode 100644 index 0000000..28b0ed3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/function_objects.hpp @@ -0,0 +1,1374 @@ +/** + * @file /include/ecl/utilities/function_objects.hpp + * + * @brief Functional objects and generators. + * + * @date June 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_UTILITIES_FUNCTION_OBJECTS_HPP_ +#define ECL_UTILITIES_FUNCTION_OBJECTS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../utilities/references.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +/***************************************************************************** +** Interface [NullaryFunction] +*****************************************************************************/ +/** + * @brief Virtual interface definition for nullary function objects. + * + * Virtual interface definition for nullary function objects (i.e. functions + * that take no arguments). + * + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFunction { +public: + typedef R result_type; /**< @brief The result type. **/ + virtual result_type operator()() = 0; /**< @brief Virtual function call required by nullary function objects. **/ + virtual ~NullaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ +}; + +/***************************************************************************** +** Interface [UnaryFunction] +*****************************************************************************/ + +/** + * @brief Virtual interface definition for unary function objects. + * + * Virtual interface definition for unary function objects (i.e. functions + * that take a single arguments). + * + * @tparam A : the argument type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFunction { +public: + typedef R result_type; /**< @brief The result type. **/ + typedef A argument_type; /**< @brief The first argument type. **/ + /** + * @brief Virtual function call required by unary function objects. + * @param arg : the argument. + **/ + virtual result_type operator()(argument_type arg) = 0; /**<@brief Virtual function call required by unary function objects. **/ + virtual ~UnaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ +}; + +/***************************************************************************** +** Interface [BinaryFunction] +*****************************************************************************/ +/** + * @brief Virtual interface definition for binary function objects. + * + * Virtual interface definition for binary function objects (i.e. functions + * that take a pair of arguments). + * + * @tparam R : the return type. + * @tparam A1 : the first argument type. + * @tparam A2 : the second argument type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class BinaryFunction { +public: + typedef R result_type; /**< @brief The result type. **/ + typedef A1 first_argument_type; /**< @brief The first argument type. **/ + typedef A2 second_argument_type; /**< @brief The second argument type. **/ + /** + * @brief Virtual function call required by binary function objects. + * + * Virtual function call required by binary function objects. + * @param arg1 : the first argument. + * @param arg2 : the second argument. + **/ + virtual result_type operator()(first_argument_type arg1, second_argument_type arg2) = 0; /**<@brief Virtual function call required by binary function objects. **/ + virtual ~BinaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ +}; + +/***************************************************************************** +** Interface [FreeFunctions] +*****************************************************************************/ +/** + * @brief Nullary function object for void global/static functions. + * + * Creates a function object from a void global/static function. + * + * @tparam R : the return type. + * + * @sa ecl::utilities::NullaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFreeFunction : public NullaryFunction +{ +public: + /** + * @brief Nullary function object constructor for global/static functions with no args. + * + * Accepts a global/static function with no args and builds the function object around it. + * + * @param function : the global/static function. + */ + NullaryFreeFunction( R (*function)() ) : free_function(function) {} + virtual ~NullaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the composited global/static function. + * + * @return R : the function's return value. + */ + R operator()() { return free_function(); } + +private: + R (*free_function)(); +}; + +/** + * @brief Specialisation for free nullary functions that return void. + * + * Specialisation for free nullary functions that return void. + * + * @sa NullaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template <> +class NullaryFreeFunction : public NullaryFunction +{ +public: + /** + * @brief Nullary function object constructor for void global/static functions with no args. + * + * Accepts a void global/static function with no args and builds the function object around it. + * + * @param function : the global/static function. + */ + NullaryFreeFunction( void (*function)() ) : free_function(function) {} + + virtual ~NullaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the composited global/static function. + * + * @return R : the function's return value. + */ + void operator()() { free_function(); } + +private: + void (*free_function)(); +}; + +/** + * @brief Unary function object for global/static functions. + * + * Creates a function object from a global/static function with a single argument. + * + * @sa generateFunctionObject + * + * @tparam A : the argument type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFreeFunction : public UnaryFunction +{ +public: + /** + * @brief Unary function object constructor for global/static functions. + * + * Accepts a global/static function with a single argument and builds + * the function object around it. + * + * @param function : a global/static function with a single argument. + */ + UnaryFreeFunction( R (*function)(A) ) : free_function(function) {} + + virtual ~UnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief A unary function object call. + * + * Redirects the unary function object call to the composited global/static function. + * + * @return R : the function's return value. + */ + R operator()(A a) { return free_function(a); } + +private: + R (*free_function)(A); +}; + +/** + * @brief Specialisations for free unary functions with no return type. + * + * Specialisations for free unary functions with no return type. + * + * @tparam A : the argument type. + * + * @sa ecl::utilities::UnaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFreeFunction : public UnaryFunction +{ +public: + /** + * @brief Unary function object constructor for global/static unary functions with no return type. + * + * Accepts a void global/static function with a single argument and builds + * the function object around it. + * + * @param function : a global/static function with a single argument. + */ + UnaryFreeFunction( void (*function)(A) ) : free_function(function) {} + + virtual ~UnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A unary function object call. + * + * Redirects the unary function object call to the composited void global/static function. + * + * @return R : the function's return value. + */ + void operator()(A a) { free_function(a); } + +private: + void (*free_function)(A); +}; + +/***************************************************************************** +** Interface [BoundFreeFunctions] +*****************************************************************************/ +/** + * @brief Nullary function object for bound unary global/static functions. + * + * Binds the argument to a unary global/static function and uses this to + * construct a nullary function object. + * + * Usage: + * @code + * void f(int i) {} + * + * int main() { + * BoundUnaryFreeFunction function_object(f,1); + * function_object(); + * } + * @endcode + * + * Note, often the use of generateFunctionObject is simpler. + * + * @tparam A : the type of the argument to be bound. + * @tparam R : the return type. + * + * @sa ecl::utilities::BoundUnaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class BoundUnaryFreeFunction : public NullaryFunction +{ +public: + /** + * @brief Binds a unary function and creates a nullary function object. + * + * Accepts both the function and a value for its single argument, binds them + * and creates a nullary function object. + * @param function : the unary global/static function. + * @param a : the argument to bind. + */ + BoundUnaryFreeFunction( R (*function)(A), A a ) : free_function(function), argument(a) {} + virtual ~BoundUnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A nullary function object call. + * + * Redirects the function object call to the bound global/static function. + * + * @return R : the function's return value. + */ + R operator()() { return free_function(argument); } + +private: + R (*free_function)(A); + A argument; +}; + +/** + * @brief Specialisation for bound void unary functions. + * + * Specialises BoundUnaryFreeFunction for functions with no return type. + * + * @tparam A : the type of the argument to be bound. + * + * @sa ecl::utilities::BoundUnaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class BoundUnaryFreeFunction : public NullaryFunction +{ +public: + /** + * @brief Binds a unary function and creates a nullary function object. + * + * Accepts both the function and a value for its single argument, binds them + * and creates a nullary function object. + * @param function : the unary global/static function. + * @param a : the argument to bind. + */ + BoundUnaryFreeFunction( void (*function)(A), A a ) : free_function(function), argument(a) {} + virtual ~BoundUnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the bound global/static function. + * + * @return void : the function's return value. + */ + void operator()() { free_function(argument); } + +private: + void (*free_function)(A); + A argument; +}; + +/***************************************************************************** + * Interface [MemberFunctions] + ***************************************************************************** + * Could make copies+refs here, just like mem_fun and mem_fun_ref but I can't + * see the need for copy style setups. + ****************************************************************************/ + +/** + * @brief Unary function object for member functions without arguments. + * + * Creates a function object from a member function without arguments + * (note, the single argument to this unary function object is the class + * instance itself). + * + * Usage: + * @code + * class A { + * public: + * void f() { //... + * } + * }; + * + * int main() { + * A a; + * NullaryMemberFunction function_object(&A::f); + * function_object(a); + * } + * @endcode + * + * @tparam C : the member function's class type type. + * @tparam R : the return type. + * + * @sa ecl::utilities::NullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryMemberFunction : public UnaryFunction { +public: + /** + * @brief Unary function object constructor for member functions without arguments. + * + * Accepts a void member function, and builds + * the function object around it. + * + * @param function : a void member function. + */ + NullaryMemberFunction( R (C::*function)()) : member_function(function) {} + virtual ~NullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + + /** + * @brief A unary function object call. + * + * Uses the specified class instance to redirect the function call to the + * void member function. + * + * @param class_object : the member function's class instance. + * @return R : the function's return value. + */ + R operator()(C &class_object) { + return (class_object.*member_function)(); + } +private: + R (C::*member_function)(); +}; + +/** + * @brief Specialisation of the unary function object for void member functions without arguments. + * + * Specialisation for a function object from a void member function without arguments (note, the single + * argument to this unary function object is the class instance itself). + * + * @tparam C : the member function's class type type. + * + * @sa ecl::utilities::NullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryMemberFunction : public UnaryFunction { +public: + /** + * @brief Unary function object constructor for void member functions. + * + * Accepts a void member function without arguments, and builds + * the function object around it. + * + * @param function : a void member function. + */ + NullaryMemberFunction( void (C::*function)()) : member_function(function) {} + virtual ~NullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief A unary function object call. + * + * Uses the specified class instance to redirect the function call to the + * void member function. + * + * @param class_object : the member function's class instance. + */ + void operator()(C &class_object) { + (class_object.*member_function)(); + } +private: + void (C::*member_function)(); +}; + +/** + * @brief Binary function object for unary member functions. + * + * Creates a function object from a unary member function. + * + * Usage: + * @code + * class A { + * public: + * void f(int i) { //... + * } + * }; + * + * int main() { + * A a; + * UnaryMemberFunction function_object(&A::f); + * function_object(a,1); + * } + * @endcode + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the return type. + * + * @sa ecl::utilities::UnaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryMemberFunction : public BinaryFunction { +public: + /** + * @brief Binary function object constructor for unary member functions. + * + * Accepts a unary member function, and builds + * the function object around it. + * + * @param function : a unary member function. + */ + UnaryMemberFunction( R (C::*function)(A)) : member_function(function) {} + virtual ~UnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A binary function object call. + * + * Uses the specified class instance and argument to redirect the function call to the + * unary member function. + * + * @param class_object : the member function's class instance. + * @param a : the member function's argument value. + * @return R : the function's return value. + */ + R operator()(C &class_object, A a) { + return (class_object.*member_function)(a); + } +private: + R (C::*member_function)(A); +}; + +/** + * @brief Specialisation of the binary function object for void unary member functions. + * + * Specialises the binary member function object for void member functions. + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * + * @sa ecl::utilities::UnaryMemberFunction @sa generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryMemberFunction : public BinaryFunction { +public: + /** + * @brief Binary function object constructor for unary member functions. + * + * Accepts a unary member function, and builds + * the function object around it. + * + * @param function : a unary member function. + */ + UnaryMemberFunction( void (C::*function)(A)) : member_function(function) {} + virtual ~UnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A binary function object call. + * + * Uses the specified class instance and argument to redirect the function call to the + * unary member function. + * + * @param class_object : the member function's class instance. + * @param a : the member function's argument value. + * @return R : the function's return value. + */ + void operator()(C &class_object, A a) { + (class_object.*member_function)(a); + } +private: + void (C::*member_function)(A); +}; + +/***************************************************************************** +** Interface [BoundMemberFunctions] +*****************************************************************************/ + +/** + * @brief Nullary function object for bound nullary member functions. + * + * Binds the class instance for a nullary member function and uses this to + * construct a nullary function object. + * + * Usage: + * @code + * class A { + * public: + * void f() { //... + * } + * + * int main() { + * A a; + * BoundNullaryMemberFunction function_object(&A::f,a); + * function_object(); + * } + * @endcode + * + * @tparam C : the member function's class type. + * @tparam R : the return type. + * + * @sa ecl::utilities::BoundNullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class BoundNullaryMemberFunction : public NullaryFunction { +public: + /** + * @brief Binds a unary member function and creates a nullary function object. + * + * Accepts the function pointer and class instance, binds them + * and creates a nullary function object. + * @param function : the void member function. + * @param class_object : the member function's class instance. + */ + BoundNullaryMemberFunction( R (C::*function)(), C &class_object) : + member_class(class_object), + member_function(function) + {} + virtual ~BoundNullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the bound member function. + * + * @return R : the function's return value. + */ + R operator()() { return (member_class.*member_function)(); } + +private: + C &member_class; + R (C::*member_function)(); +}; + +/** + * @brief Specialisation of the bound nullary member function for void functions. + * + * Binds the class instance for a nullary member function and uses this to + * construct a nullary function object. This is the specialisation for nullary + * member functions with void return type. + * + * @tparam C : the member function's class type. + * + * @sa ecl::utilities::BoundNullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects". + */ +template +class BoundNullaryMemberFunction : public NullaryFunction { +public: + /** + * @brief Binds a unary member function and creates a nullary function object. + * + * Accepts the function pointer and class instance, binds them + * and creates a nullary function object. + * @param function : the void member function. + * @param class_object : the member function's class instance. + */ + BoundNullaryMemberFunction( void (C::*function)(), C &class_object) : + member_class(class_object), + member_function(function) + {} + + virtual ~BoundNullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the bound member function. + */ + void operator()() { (member_class.*member_function)(); } + +private: + C &member_class; + void (C::*member_function)(); +}; + +/** + * @brief Unary function object for partially bound unary member functions. + * + * Binds the class instance but not the argument for a unary member function and uses this to + * construct a unary function object. + * + * Usage: + * @code + * class A { + * public: + * void f(int i) { //... + * } + * + * int main() { + * A a; + * PartiallyBoundUnaryMemberFunction function_object(&A::f,a); + * function_object(1); + * } + * @endcode + * + * @sa generateFunctionObject + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class PartiallyBoundUnaryMemberFunction : public UnaryFunction { +public: + /** + * @brief Binds a unary member function and creates a nullary function object. + * + * Accepts the function, class instance only (not the argument), binds them + * and creates a unary function object. + * @param function : the unary global/static function. + * @param class_object : the member function's class instance. + */ + PartiallyBoundUnaryMemberFunction( R (C::*function)(A), C &class_object) : + member_class(class_object), + member_function(function) + {} + virtual ~PartiallyBoundUnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A unary function object call. + * + * Redirects the unary function object call to the bound member function. + * + * @param a : the argument passed to the function. + * @return R : the function's return value. + */ + R operator()(A a) { + return (member_class.*member_function)(a); + } +private: + C &member_class; + void (C::*member_function)(A); +}; +/** + * @brief Nullary function object for bound unary member functions. + * + * Binds the class instance and argument for a unary member function and uses this to + * construct a nullary function object. + * + * Usage: + * @code + * class A { + * public: + * void f(int i) { //... + * } + * + * int main() { + * A a; + * BoundUnaryMemberFunction function_object(&A::f,a,1); + * function_object(); + * } + * @endcode + * + * @sa generateFunctionObject + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class BoundUnaryMemberFunction : public NullaryFunction { +public: + /** + * @brief Binds a unary member function and creates a nullary function object. + * + * Accepts the function, class instance and a value for its single argument, binds them + * and creates a nullary function object. + * @param function : the unary global/static function. + * @param class_object : the member function's class instance. + * @param a : the value of the argument to bind. + */ + BoundUnaryMemberFunction( R (C::*function)(A), C &class_object, A a) : + member_class(class_object), + member_function(function), + argument(a) + {} + virtual ~BoundUnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A nullary function object call. + * + * Redirects the nullary function object call to the bound member function. + * + * @return R : the function's return value. + */ + R operator()() { + return (member_class.*member_function)(argument); + } +private: + C &member_class; + void (C::*member_function)(A); + A argument; +}; + +/** + * @brief Binary function object for partially bound binary member functions. + * + * Binds the class instance but not the arguments for a binary member function and uses this to + * construct a binary function object. + * + * Usage: + * @code + * class A { + * public: + * void f(int i, string n) { //... + * } + * + * int main() { + * A a; + * PartiallyBoundBinaryMemberFunction function_object(&A::f,a); + * function_object(1,"dude"); + * } + * @endcode + * + * @sa generateFunctionObject + * + * @tparam C : the member function's class type. + * @tparam A : the member function's first argument type. + * @tparam B : the member function's second argument type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class PartiallyBoundBinaryMemberFunction : public BinaryFunction { +public: + /** + * @brief Binds a binary member function and creates a binary function object. + * + * Accepts the function, class instance only (not the arguments), binds them + * and creates a binary function object. + * @param function : the unary global/static function. + * @param class_object : the member function's class instance. + */ + PartiallyBoundBinaryMemberFunction( R (C::*function)(A, B), C &class_object) : + member_class(class_object), + member_function(function) + {} + virtual ~PartiallyBoundBinaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief A binary function object call. + * + * Redirects the binary function object call to the bound member function. + * + * @param a : the first argument passed to the function (type A). + * @param b : the second argument passed to the function (type B). + * @return R : the function's return value. + */ + R operator()(A a, B b) { + return (member_class.*member_function)(a, b); + } +private: + C &member_class; + void (C::*member_function)(A, B); +}; +/***************************************************************************** +** Function Object Wrappers +*****************************************************************************/ +/** + * @brief Create a NullaryFunction object composited from an existing function object. + * + * Takes a nullary function object (strictly by definition) and creates a + * NullaryFunction child object. This + * is useful in utilising the inheritance from NullaryFunction (needed for slots + * and similar classes). + * + * @tparam FunctionObject : type of the function object to be wrapped. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFunctionCopy : public NullaryFunction +{ +public: + /** + * @brief NullaryFunction child constructor for nullary function objects. + * + * Creates a child of the NullaryFunction class by copying a nullary function + * object (one that is purely by definition). + * + * @param f_o : the function object to be assigned to the NullaryFunction child. + */ + NullaryFunctionCopy(const FunctionObject &f_o ) : function_object(f_o) { + ecl_compile_time_concept_check(NullaryFunction); + } + virtual ~NullaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The nullary function object call. + * + * Redirects the call to the composited nullary function object call. + * + * @return R : the function's return value. + */ + Result operator()() { return function_object(); } + +private: + FunctionObject function_object; +}; + +/** + * @brief Specialisation of NullaryFunctionCopy for void return types. + * + * Specialises the NullaryFunctionCopy class for void return types. + * + * @tparam FunctionObject : type of the function object to be wrapped. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFunctionCopy : public NullaryFunction +{ +public: + /** + * @brief NullaryFunction child constructor for nullary function objects. + * + * Creates a child of the NullaryFunction class by copying a nullary function + * object (one that is purely by definition). + * + * @param f_o : the function object to be assigned to the NullaryFunction child. + */ + explicit NullaryFunctionCopy( const FunctionObject &f_o ) : function_object(f_o) { + ecl_compile_time_concept_check(NullaryFunction); + } + virtual ~NullaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The nullary function object call. + * + * Redirects the call to the composited nullary function object call. + */ + void operator()() { function_object(); } + +private: + FunctionObject function_object; +}; + +/** + * @brief Creates a nullary function from a reference wrapper. + * + * Takes a reference wrapper containing a nullary function (strictly by definition) object + * reference and creates a NullaryFunction descendant. This + * is useful in utilising the inheritance from NullaryFunction (needed for slots + * and similar classes). + * + * @tparam FunctionObject : type of the function object to be referenced. + * @tparam Result : the return type of the nullary function. + * + * @sa NullaryFunctionReference, @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFunctionReference : public NullaryFunction +{ +public: + /** + * @brief Creates a NullaryFunction descendant from a reference wrapper. + * + * Creates a NullaryFunction descendant by reference (not copying). + * + * @param wrapper : the reference wrapper holding the nullary function object to be referenced. + */ + explicit NullaryFunctionReference( const ReferenceWrapper &wrapper ) : function_object(wrapper.reference()) { + ecl_compile_time_concept_check(NullaryFunction); + } + virtual ~NullaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The nullary function object call. + * + * Redirects the call to the referenced nullary function object call. + * + * @return R : the function's return value. + */ + Result operator()() { return function_object(); } + +private: + FunctionObject &function_object; +}; + +/** + * @brief Creates a void nullary function from a reference wrapper. + * + * Takes a reference wrapper containing a nullary function (strictly by definition) object + * reference and creates a NullaryFunction descendant. This + * is a specialisation which caters to nullary function objects with void return type. + * + * @tparam FunctionObject : type of the function object to be referenced. + * + * @sa NullaryFunctionReference, @ref functionobjectsGuide "FunctionObjects". + */ +template +class NullaryFunctionReference< FunctionObject, void > : public NullaryFunction +{ +public: + /** + * @brief Creates a NullaryFunction descendant from a reference wrapper. + * + * Creates a NullaryFunction descendant by reference (not copying). + * + * @param wrapper : the reference wrapper holding the nullary function object to be referenced. + */ + explicit NullaryFunctionReference( const ReferenceWrapper &wrapper ) : function_object(wrapper.reference()) { + ecl_compile_time_concept_check(NullaryFunction); + } + virtual ~NullaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The nullary function object call. + * + * Redirects the call to the referenced nullary function object call. + */ + void operator()() { function_object(); } + +private: + FunctionObject &function_object; +}; + +/** + * @brief Create a UnaryFunction object composited from an existing function object. + * + * Takes a unary function object (strictly by definition) and creates a + * UnaryFunction child object. This + * is useful in utilising the inheritance from UnaryFunction (needed for slots + * and similar classes). + * + * @tparam FunctionObject : type of the function object to be wrapped. + * @tparam T : the unary data type. + * @tparam R : the return type. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFunctionCopy : public UnaryFunction +{ +public: + /** + * @brief UnaryFunction child constructor for unary function objects. + * + * Creates a child of the UnaryFunction class by copying a unary function + * object (one that is purely by definition). + * + * @param f_o : the function object to be assigned to the UnaryFunction child. + */ + UnaryFunctionCopy(const FunctionObject &f_o ) : function_object(f_o) { +// ecl_compile_time_concept_check(UnaryFunction); + } + virtual ~UnaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The unary function object call. + * + * Redirects the call to the composited nullary function object call. + * + * @return R : the function's return value. + */ + Result operator()(T t) { return function_object(t); } + +private: + FunctionObject function_object; +}; + +/** + * @brief Specialisation of UnaryFunctionCopy for void return types. + * + * Specialises the UnaryFunctionCopy class for void return types. + * + * @tparam FunctionObject : type of the function object to be wrapped. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFunctionCopy : public UnaryFunction +{ +public: + /** + * @brief UnaryFunction child constructor for unary function objects. + * + * Creates a child of the UnaryFunction class by copying a unary function + * object (one that is purely by definition). + * + * @param f_o : the function object to be assigned to the UnaryFunction child. + */ + explicit UnaryFunctionCopy( const FunctionObject &f_o ) : function_object(f_o) { +// ecl_compile_time_concept_check(UnaryFunction); + } + virtual ~UnaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The unary function object call. + * + * Redirects the call to the composited unary function object call. + */ + void operator()(T t) { function_object(t); } + +private: + FunctionObject function_object; +}; + +/** + * @brief Creates a unary function from a reference wrapper. + * + * Takes a reference wrapper containing a unary function (strictly by definition) object + * reference and creates a UnaryFunction descendant. This + * is useful in utilising the inheritance from UnaryFunction (needed for slots + * and similar classes). + * + * @tparam FunctionObject : type of the function object to be referenced. + * @tparam Result : the return type of the unary function. + * + * @sa UnaryFunctionReference, @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFunctionReference : public UnaryFunction +{ +public: + /** + * @brief Creates a UnaryFunction descendant from a reference wrapper. + * + * Creates a UnaryFunction descendant by reference (not copying). + * + * @param wrapper : the reference wrapper holding the unary function object to be referenced. + */ + explicit UnaryFunctionReference( const ReferenceWrapper &wrapper ) : function_object(wrapper.reference()) { +// ecl_compile_time_concept_check(UnaryFunction); + } + + virtual ~UnaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + /** + * @brief The unary function object call. + * + * Redirects the call to the referenced unary function object call. + * + * @return R : the function's return value. + */ + Result operator()(T t) { return function_object(t); } + +private: + FunctionObject &function_object; +}; + +/** + * @brief Creates a void unary function from a reference wrapper. + * + * Takes a reference wrapper containing a unary function (strictly by definition) object + * reference and creates a UnaryFunction descendant. This + * is a specialisation which caters to unary function objects with void return type. + * + * @tparam FunctionObject : type of the function object to be referenced. + * + * @sa UnaryFunctionReference, @ref functionobjectsGuide "FunctionObjects". + */ +template +class UnaryFunctionReference< ReferenceWrapper, T, void > : public UnaryFunction +{ +public: + typedef typename ReferenceWrapper::type FunctionObject; /**< The wrapper's function object reference type. **/ + /** + * @brief Creates a UnaryFunction descendant from a reference wrapper. + * + * Creates a UnaryFunction descendant by reference (not copying). + * + * @param wrapper : the reference wrapper holding the unary function object to be referenced. + */ + explicit UnaryFunctionReference( const ReferenceWrapper &wrapper ) : function_object(wrapper.reference()) { +// ecl_compile_time_concept_check(UnaryFunction); + } + virtual ~UnaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/ + + /** + * @brief The unary function object call. + * + * Redirects the call to the referenced unary function object call. + */ + void operator()(T t) { function_object(t); } + +private: + FunctionObject &function_object; +}; + +/***************************************************************************** +** Nullary Function Generators +*****************************************************************************/ + +/** + * @brief Generate a nullary function object from a void global/static function. + * + * Overloaded function type, this particular overload generates a nullary + * function object from a void global/static function. + * + * @tparam R : the return type. + * @param function : the void global/static function. + * @return NullaryFreeFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +NullaryFreeFunction generateFunctionObject( R (*function)() ) { + return NullaryFreeFunction( function ); +} + +/** + * @brief Generate a unary function object from a unary global/static function. + * + * Overloaded function type, this particular overload generates a unary + * function object from a unary global/static function. + * + * @tparam A : the function's argument type. + * @tparam R : the function's return type. + * @param function : the unary global/static function. + * @return UnaryFreeFunction : unary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +UnaryFreeFunction generateFunctionObject( R (*function)(A) ) { + return UnaryFreeFunction( function ); +} + +/** + * @brief Generate a nullary function object from a bound unary global/static function. + * + * Overloaded function type, this particular overload generates a nullary + * function object from a bound unary global/static function. + * + * @tparam A : the function's argument type. + * @tparam R : the return type. + * @tparam I : a mask for the function's argument type. + * @param function : the void global/static function. + * @param a : the argument value to bind. + * @return BoundUnaryFreeFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +BoundUnaryFreeFunction generateFunctionObject( R (*function)(A), I& a ) { + return BoundUnaryFreeFunction( function, a ); +} + +/** + * @brief Generate a nullary function object from a bound unary global/static function. + * + * Overloaded function type, this particular overload generates a nullary + * function object from a bound unary global/static function (with supplied const argument). + * The const argument bind allows for binding from temporaries. + * + * @tparam A : the function's argument type. + * @tparam R : the return type. + * @tparam I : a mask for the function's argument type. + * @param function : the void global/static function. + * @param a : the argument value to bind (const). + * @return BoundUnaryFreeFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +BoundUnaryFreeFunction generateFunctionObject( R (*function)(A), const I& a ) { + return BoundUnaryFreeFunction( function, a ); +} + +/** + * @brief Generate a unary function object from a nullary member function. + * + * Overloaded function type, this particular overload generates a unary + * function object from a void member function. + * + * @tparam C : the member function's class type. + * @tparam R : the member function's return type. + * @param function : the void member function. + * @return NullaryMemberFunction : unary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +NullaryMemberFunction generateFunctionObject( R (C::*function)() ) { + return NullaryMemberFunction( function ); +} + +/** + * @brief Generate a nullary function object by binding a nullary member function with its instance. + * + * Overloaded function type, this particular overload generates a nullary + * function object by binding the class instance to a void member function. + * + * @tparam C : the member function's class type. + * @tparam R : the member function's return type. + * @param function : the void member function. + * @param c : the member function's class instance. + * @return NullaryMemberFunction : unary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +BoundNullaryMemberFunction generateFunctionObject( R (C::*function)(), C &c ) { + return BoundNullaryMemberFunction( function, c ); +} + +/** + * @brief Generate a binary function object from a unary member function. + * + * Overloaded function type, this particular overload generates a binary + * function object from a unary member function. + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the member function's return type. + * @param function : the unary member function. + * @return UnaryMemberFunction : binary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +UnaryMemberFunction generateFunctionObject( R (C::*function)(A) ) { + return UnaryMemberFunction( function ); +} + +/** + * @brief Generate a unary function object by partially binding a unary member function. + * + * Overloaded function type, this particular overload generates a unary + * function object by binding the class instance but not the argument to + * a unary member function. + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the member function's return type. + * + * @param function : the void member function. + * @param c : the member function's class instance. + * @return PartiallyBoundUnaryMemberFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +PartiallyBoundUnaryMemberFunction generateFunctionObject( R (C::*function)(A), C& c) { + return PartiallyBoundUnaryMemberFunction( function, c); +} + +/** + * @brief Generate a nullary function object by binding a unary member function. + * + * Overloaded function type, this particular overload generates a nullary + * function object by binding the class instance and argument to a unary member function. + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the member function's return type. + * @tparam I : a mask for the function's argument type. + * @param function : the void member function. + * @param c : the member function's class instance. + * @param a : the argument value to bind. + * @return BoundUnaryMemberFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +BoundUnaryMemberFunction generateFunctionObject( R (C::*function)(A), C& c, I& a ) { + // The I here is a bit of a trick...if you use A in the constructor above instead of I + // then it gets confused trying to deduce A as often the function arg and the input value + // are different types (e.g. const int& as opposed to int). So fix A in the template + // direction first, then pass it a type I which can be converted on the fly where needed. + return BoundUnaryMemberFunction( function, c, a ); +} + +/** + * @brief Generate a nullary function object by binding a unary member function. + * + * Overloaded function type, this particular overload generates a nullary + * function object by binding the class instance and argument to a unary member function. + * The const argument bind allows for binding from temporaries. + * + * @tparam C : the member function's class type. + * @tparam A : the member function's argument type. + * @tparam R : the member function's return type. + * @tparam I : a mask for the function's argument type. + * @param function : the void member function. + * @param c : the member function's class instance. + * @param a : the argument value to bind (const). + * @return BoundUnaryMemberFunction : nullary function object. + * + * @sa @ref functionobjectsGuide "FunctionObjects". + */ +template +BoundUnaryMemberFunction generateFunctionObject( R (C::*function)(A), C& c, const I& a ) { + // This one differs from the previous due to the const reference - this allows things like + // temporaries to pass through unscathed to a function with an argument like const int&. + return BoundUnaryMemberFunction( function, c, a ); +} + +} // namespace ecl + +#endif /* ECL_UTILITIES_FUNCTION_OBJECTS_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/parameter.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/parameter.hpp new file mode 100644 index 0000000..770fd2c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/parameter.hpp @@ -0,0 +1,115 @@ +/** + * @file /include/ecl/utilities/parameter.hpp + * + * @brief Defines a formalised interface for class parameters. + * + * A templatised construct that defines access and configuration + * interfaces for a simple parameter type embedded in a class. + * + * @date April 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_UTILITIES_PARAMETER_HPP_ +#define ECL_UTILITIES_PARAMETER_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Parameter +*****************************************************************************/ +/** + * @brief General parameter type for member variables of a pre-specified class. + * + * A Parameter is a templatised construct that formally defines an interface to + * a simple type embedded in a class. + * + * Usage: + * + * Definition: + * @code + * class A { + * public: + * Parameter counter; + * }; + * @endcode + * and usage (like get/set, but much less verbose): + * @code + * + * int main() { + * A a; + * a.counter(1); // <-- Sets the variable. + * a.counter = 1; // <-- This is also ok. + * cout << a.counter(); << endl; // <-- Gets the variable. + * } + * @endcode + * + * @sa src/test/core/parameters.cpp, @ref parametersGuide "Parameters" + * + **/ +template class Parameter { + public: + explicit Parameter() : parameter() {}; /**< Configures the parameter with the type's default value. **/ + /** + * Configures the parameter with a specified value. + * @param value : the value to instantiate the parameter with. + */ + Parameter(const T& value) : parameter(value){}; + + virtual ~Parameter() {} + + /****************************************** + ** Operator = + *******************************************/ + /** + * @brief Allow assignment from the underlying type. + * + * Note that this does not help with conversions for construction (or + * in argument passing to functions, because that is construction also). + * + * @param value : the value to configure the internal variable with. + */ + void operator =(const T& value) { parameter = value; } + /** + * Convenience operator so that it can be treated as a normal variable if you wish + * (i.e. no () call needed). + * Note that we do not permit the returned reference to be modified as doing so + * would mean this class loses control of the variable. + * + * @return T& : a const reference to the parameter's variable. + */ + operator const T&() const { return parameter; } + + /****************************************** + ** Operator () + *******************************************/ + /** + * Formal access to the parameter's variable. + * Note that we do not permit the returned reference to be modified as doing so + * would mean this class loses control of the variable. + * + * @return T& : a reference to the parameter's variable. + */ + const T& operator ()() const { return parameter; } + /** + * Formal setting operator for the parameter's variable. + * Note that we dont need the reference here since we're copying into the private + * variable - you get the same number of constructions either way. + * + * @param value : the value to configure the internal variable with. + */ + void operator ()( const T& value ) { parameter = value; } + + private: + T parameter; +}; + +} // namespace ecl + +#endif /*ECL_UTILITIES_PARAMETER_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/references.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/references.hpp new file mode 100644 index 0000000..0bc6d13 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/references.hpp @@ -0,0 +1,185 @@ +/** + * @file /include/ecl/utilities/references.hpp + * + * @brief Defines a reference wrapper for c++ objects. + * + * Reference wrappers are soon coming to c++, these definitions will work + * until that time. + * + * @date July 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_UTILITIES_REFERENCE_WRAPPER_HPP_ +#define ECL_UTILITIES_REFERENCE_WRAPPER_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Wrappers +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Returns the address of an object (uses correct c++ syntactics). + * + * @param v : the object located at this address. + * @return T* : a pointer to the object. + * + * @tparam T : the type of the object. + */ +template +T* addressOf( T & v ) { + return reinterpret_cast( + &const_cast(reinterpret_cast(v))); +} +/** + * @brief Provides a wrapper which allows the original object to be passed like a reference. + * + * This class wraps the supplied object, storing it as a pointer and allowing it + * to be passed like a regular object. By itself, this is not terribly useful, but + * in combination with the ref/cref functions and also the is_reference_wrapper trait, + * it allows things like functions and function objects to be easily manipulated. + * + * Note: reference wrappers might seem a bit redundant - why do we need them? + * The following case illustrates a desired usage scenario. + * + * @code + class A { + public: + template + void f(T i) { cout << "Not a reference input" << endl; } + + template + void f(T &i) { cout << "A reference input" << endl; } + } + @endcode + * Unfortunately, when you come to call this function, you'll get an ambiguity error. + * + * In these situations you can use a simple function call (not ref) and pass in this + * reference wrapper: + * @code + class A { + public: + template + void f(const T &t) { + if ( is_reference_wrapper ) { + // do something for references + } else { + // do something for non-references + } + } + } + @endcode + * + * @tparam T : the type of object this class is wrapping. + */ +template +class ReferenceWrapper { + +public: + typedef T type; /**< Convenient handle to the reference wrapper's base type. **/ + + /** + * @brief Constructs the wrapper around the supplied object instance. + * + * Constructs the wrapper around the supplied object instance. + * + * @param t : the object instance. + */ + ReferenceWrapper(T& t): obj_ptr(addressOf(t)) {} + + virtual ~ReferenceWrapper() {} + + /** + * @brief Convenience operator for converting to the underlying reference directly. + * + * When used where the underlying reference is expected, this automatically handles + * the conversion. + * + * @return T& : the returned reference to the wrapped object. + */ + operator T& () const { return *obj_ptr; } + + /** + * @brief Accessor to the reference of the original instance. + * + * Returns a reference to the wrapped object. + * + * @return T& : the returned reference to the wrapped object. + */ + T& reference() const { return *obj_ptr; } + + /** + * @brief Accessor to a pointer to the original instance. + * + * Returns a pointer to the wrapped object. + * + * @return T& : the returned pointer to the wrapped object. + */ + T* pointer() const { return *obj_ptr; } + +private: + T* obj_ptr; +}; + +/***************************************************************************** +** Utility Functions +*****************************************************************************/ + +/** + * This is a simple means of instantiating a reference wrapper. + * + * This is a simple means of instantiating a reference wrapper. + * @param wrapped_object : the object to be referenced. + * @return ReferenceWrapper : the wrapper. + */ +template +ReferenceWrapper ref(T &wrapped_object) { + return ReferenceWrapper(wrapped_object); +} + +/** + * This is a simple means of instantiating a const reference wrapper. + * + * This is a simple means of instantiating a const reference wrapper. + * @param wrapped_object : the object to be referenced. + * @return const ReferenceWrapper : the wrapper. + */ +template +ReferenceWrapper cref(T const &wrapped_object) { + return ReferenceWrapper(wrapped_object); +} + +/** + * @brief Default action for detection of the reference wrapper type trait (false). + * + * Sets the default value (false) for detection of the reference wrapper type trait. + * Specialisations enable this to true. + * + * @tparam T : the test type. + */ +template +class is_reference_wrapper : public False {}; + +/** + * @brief Configures the reference wrapper type trait for the ReferenceWrapper specialisation to true. + * + * Configures the reference wrapper type trait for ReferenceWrapper objects to true. + * + * @tparam T : the object wrapped by ReferenceWrapper. + */ +template +class is_reference_wrapper< ReferenceWrapper > : public True {}; + +} // namespace ecl + + +#endif /* ECL_UTILITIES_REFERENCE_WRAPPER_HPP_ */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/singleton.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/singleton.hpp new file mode 100644 index 0000000..de6c4bc --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/singleton.hpp @@ -0,0 +1,70 @@ +/** + * @file /include/ecl/utilities/singleton.hpp + * + * @brief Singleton construction via the curiously recurring template pattern. + * + * Enables singletons created via the curiously recurring template pattern. + * See the wikipedia entry on singletons for more detail. + * + * @sa @ref singletonsGuide "Singletons" + * + * @date April, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_UTILITIES_SINGLETON_HPP_ +#define ECL_UTILITIES_SINGLETON_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Class [Singleton] +*****************************************************************************/ +/** + * @brief Singleton construction via the curiously recurring template pattern. + * + * This class doesn't provide singletons, but enables the construction of + * referenced based singletons via the curiously recurring template pattern. + * + * If you wish to create a singleton, simply: + * - inherit this class (supplying your class as the template parameter). + * - this class is declared a friend. + * - your class has a protected constructor. + * - use a macro as shown below to call it. + * + * @code + * #define Test TestObject::instance() + * + * ... + * + * cout << Test.value() << endl; + * @endcode + * + * @sa src/test/singleton.cpp, @ref singletonsGuide "Singletons" + **/ +template class Singleton +{ + public: + /** + * Stores a reference to a single instantiation of the template object. If + * the template class has a protected or private default constructor + * (no arguments), then it ensures the class will be a singleton itself. + **/ + static T& instance() + { + static T the_single_instance; // assumes T has a protected default constructor + return the_single_instance; + } + + virtual ~Singleton () {} +}; + +} // namespace ecl + +#endif /*ECL_UTILITIES_SINGLETON_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/void.hpp b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/void.hpp new file mode 100644 index 0000000..38f0573 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/include/ecl/utilities/void.hpp @@ -0,0 +1,82 @@ +/** + * @file /include/ecl/utilities/void.hpp + * + * @brief Void/null object and function definitions. + * + * A void (null) object that is occasionally useful, particularly as a + * null argument to template specialisations. Also typedefs the void + * function pointer for convenience. + * + * @sa Void. + * + * @date August 2007 + * + **/ +/***************************************************************************** +** Defines +*****************************************************************************/ + +#ifndef ECL_UTILITIES_VOID_HPP_ +#define ECL_UTILITIES_VOID_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Typedefs +*****************************************************************************/ +/** + * @brief Convenient type definition for empty functions (void pointers). + * + * Convenient type definition for empty functions (void pointers). Wherever + * you would normally use + * @code + * void(*)() + * @endcode + * you can instead replace with the more convenient + * @code + * VoidFunction + * @endcode + **/ +typedef void (*VoidFunction)(); + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @brief A void (null) object. + * + * A void (null) object that is occasionally useful for template instantiations. + * When you want to instantiate a template class without a type, just set + * its default type to this void object and create a specialisation of that + * template class. + **/ +class Void { +public: + template + friend OutputStream& operator << (OutputStream& ostream, const Void void_object); + + virtual ~Void() {} +}; + +/** + * @brief Output stream operator for Void objects. + * + * This function not serve any purpose except to allow the stream to move + * on to the next output object. + * + * @param ostream : the output stream. + * @param void_object : the void object to ignore. + * @return OutputStream : return the output stream as is. + **/ +template +OutputStream& operator << (OutputStream& ostream, const Void void_object) { (void) void_object; return ostream; } + +} // namespace ecl + + + +#endif /*ECL_UTILITIES_VOID_HPP_*/ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/package.xml b/ros2_ws/src/ecl_core/ecl_utilities/package.xml new file mode 100644 index 0000000..74a26ac --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/package.xml @@ -0,0 +1,35 @@ + + + ecl_utilities + 1.2.1 + + Includes various supporting tools and utilities for c++ programming. + + Daniel Stonier + BSD-3-Clause + http://wiki.ros.org/ecl_utilities + https://github.com/stonier/ecl_core + https://github.com/stonier/ecl_core/issues + Daniel Stonier --> + + ament_cmake_ros + + ecl_license + ecl_build + ecl_mpl + ecl_concepts + + ecl_license + ecl_mpl + ecl_concepts + + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/src/CMakeLists.txt new file mode 100644 index 0000000..198acdd --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/CMakeLists.txt @@ -0,0 +1,11 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(examples) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/src/examples/CMakeLists.txt new file mode 100644 index 0000000..89b61db --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/examples/CMakeLists.txt @@ -0,0 +1,16 @@ +############################################################################## +# Macros +############################################################################## + +macro(ecl_utilities_add_demo name) + add_executable(ecl_demo_${name} ${name}.cpp) + target_link_libraries(ecl_demo_${name} PUBLIC ${PROJECT_NAME} ecl_config::ecl_config) + set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################## +# Executables +############################################################################## + +ecl_utilities_add_demo(constructors) diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/examples/constructors.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/examples/constructors.cpp new file mode 100644 index 0000000..c3481c3 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/examples/constructors.cpp @@ -0,0 +1,94 @@ +/** + * @file /src/examples/constructors.cpp + * + * @brief Demos constructor usage on your platform. + * + * @date May, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Classes +*****************************************************************************/ + +class A { + public: + A(int i) : var(i) { (void) var; std::cout << "Constructor" << std::endl; } + A(const A& /* a */) { std::cout << "Copy constructor" << std::endl; } + ~A() { std::cout << "Destructor" << std::endl; } + void f() {}; + private: + int var; +}; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +A f() { + return A(3); +} + +A g() { + A a(4); + return a; +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Normal Constructor : A a(3)" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + A a1(3); a1.f(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Copy Constructor : A a2(a)" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + A a2(a1); a2.f(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructor Assignment w/ Function : A a3 = f();" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + A a3 = f(); a3.f(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Constructor Assignment w/ Non Temp Function : A a4 = g();" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + A a4 = g(); a4.f(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Program Finished" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + + return 0; +} +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/CMakeLists.txt b/ros2_ws/src/ecl_core/ecl_utilities/src/test/CMakeLists.txt new file mode 100644 index 0000000..007a39c --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/CMakeLists.txt @@ -0,0 +1,21 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_utilities_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Tests +############################################################################### + +ecl_utilities_add_gtest(function_objects) +ecl_utilities_add_gtest(references) +ecl_utilities_add_gtest(singleton) +ecl_utilities_add_gtest(parameters) +ecl_utilities_add_gtest(flags) diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/flags.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/test/flags.cpp new file mode 100644 index 0000000..5ebddbe --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/flags.cpp @@ -0,0 +1,178 @@ +/** + * @file /src/test/flags.cpp + * + * @brief Unit Test for the @ref ecl::Flags "Flags" class. + * + * @date February 2012 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/utilities/flags.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +#define FLAGS_DEBUG + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace utilities { +namespace tests { + +/***************************************************************************** +** Enum +*****************************************************************************/ + +enum Setting +{ + Nada = 0x00, // the empty flag. + Fast = 0x01, // Group speed + Slow = 0x02, + Bright = 0x10, // Group colour + Dark = 0x20, + Red = 0x40, + Gold = 0x80, + FastGold = 0x81, // Combinations (convenient setting and checking (w/ testFlag())) +}; + +/***************************************************************************** +** Helper Piper +*****************************************************************************/ +/** + * The helper function that makes it convenient for piping enums into a flags variable. + **/ +Flags operator|(Setting flagOne, Setting flagTwo) { return Flags(flagOne) | flagTwo; } + +enum Property +{ + Fixed = 0x01, + Dynamic = 0x02 +}; + +/** + * Useful to define your enum with the flag name and a pluralised typedef like this for + * ease of notation. + */ +typedef Flags Settings; + +/***************************************************************************** +** Illegal combination handler +*****************************************************************************/ +/** + * Restricting combinations via an accessor. + */ +class A +{ +public: + void configure(Settings s) + { + if ( ( s.testFlag(Gold) && s_.testFlag(Dark) ) || + ( s_.testFlag(Gold) && s.testFlag(Dark) ) || + ( s.testFlag(Gold) && s.testFlag(Dark) ) ) + { + #ifdef FLAGS_DEBUG + std::cout << "This combination is not permitted." << std::endl; + #endif + return; + } else { + s_ = s; + } + } + Settings settings() { return s_; } + +private: + Settings s_; +}; + +}}} // namespaces + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl::utilities::tests; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Flags, initialisation) { + + Settings settings; + settings = Fast | Red; + // settings = Fixed; // <-- Illegal call, incompatible enum used. +#ifdef FLAGS_DEBUG + std::cout << "Fast & Red: " << settings << std::endl; +#endif + EXPECT_EQ(Fast|Red,settings); +} + +TEST(Flags, Operators) { + Settings settings; + settings = Fast | Red; + settings &= Fast; // <-- Mask out everything but Fast +#ifdef FLAGS_DEBUG + std::cout << "Fast: " << settings << std::endl; +#endif + + settings |= Gold; // <-- Add gold +#ifdef FLAGS_DEBUG + std::cout << "Fast & Gold: " << settings << std::endl; +#endif + EXPECT_EQ(FastGold,settings); +} + +TEST(Flags, tests) { + Settings settings; + settings = Fast | Gold; + EXPECT_EQ(settings.testFlag(Gold),true); + EXPECT_EQ(settings.testFlag(Red),false); + EXPECT_EQ(settings.testFlag(FastGold),true); + settings.clear(); + EXPECT_EQ(settings.testFlag(Nada),true); + +#ifdef FLAGS_DEBUG + if ( settings.testFlag(Gold) ) { + std::cout << "Gold Set" << std::endl; + } else { + std::cout << "Gold Not Set" << std::endl; + } + if ( settings.testFlag(Red) ) { + std::cout << "Red Set" << std::endl; + } else { + std::cout << "Red Not Set" << std::endl; + } + if ( settings.testFlag(FastGold) ) { + std::cout << "Fast & Gold Set" << std::endl; + } else { + std::cout << "Fast & Gold Not Set" << std::endl; + } +#endif +} +TEST(Flags, combinations) { + A a; + a.configure(Gold|Dark); // fails to configure + EXPECT_EQ(0,a.settings()); + a.configure(Gold); + EXPECT_EQ(Gold,a.settings()); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/function_objects.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/test/function_objects.cpp new file mode 100644 index 0000000..1a1f98b --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/function_objects.cpp @@ -0,0 +1,199 @@ +/** + * @file /src/test/function_objects.cpp + * + * @brief Unit Test for the function objects. + * + * @date June 29, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/utilities/function_objects.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Classes +*****************************************************************************/ + +namespace ecl { +namespace utilities { +namespace tests { + +class FunctionObject { +public: + FunctionObject() : result(-1) {} + typedef void result_type; + void operator()() { + result = 0; +// std::cout << "Void function object." << std::endl; + } + int result; +}; + +class MemberFunctions { +public: + void e() { + result = 0; +// std::cout << "Member function with no arguments." << std::endl;; + } + void f(const int &i) { + (void)i; + result = 1; +// std::cout << "Member function with argument: " << i << std::endl;; + } + void g() { + result = 2; +// std::cout << "Member function" << std::endl;; + } + void h(const int& i) { + (void)i; + result = 3; +// std::cout << "Member function with ref argument: " << i << std::endl;; + } + int result; +}; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +static int free_result = -1; + +void rnf1() { + free_result = 0; +// std::cout << "Free nullary function" << std::endl;; +} + +int rnf2() { + free_result = 1; +// std::cout << "Free nullary function returning: 3" << std::endl;; + return 3; +} + +void ruf1(const int &i) { + (void)i; + free_result = 2; +// std::cout << "Free unary function with argument: " << i << std::endl;; +} + +int ruf2(const int &i) { + free_result = 3; +// std::cout << "Free unary function with argument: " << i << std::endl;; + return i; +} + +}}} + +/***************************************************************************** +** Using +*****************************************************************************/ + +using namespace ecl; +using namespace ecl::utilities::tests; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(FunctionObjects,freeFunctions) { + NullaryFreeFunction rnfo1(rnf1); + rnfo1(); + EXPECT_EQ(0,free_result); + + NullaryFreeFunction rnfo2(rnf2); + NullaryFreeFunction::result_type i1 = rnfo2(); + EXPECT_EQ(3,i1); + + UnaryFreeFunction rufo1(ruf1); + rufo1(2); + EXPECT_EQ(2,free_result); + + UnaryFreeFunction rufo2(ruf2); + UnaryFreeFunction::result_type i2 = rufo2(4); + EXPECT_EQ(4,i2); +} + +TEST(FunctionObjects,boundFreeFunctions) { + + BoundUnaryFreeFunction brufo1(ruf1,5); + brufo1(); + EXPECT_EQ(2,free_result); +} + +TEST(FunctionObjects,memberFunctions) { + + MemberFunctions a; + NullaryMemberFunction mufo1(&MemberFunctions::e); + mufo1(a); + EXPECT_EQ(0,a.result); + + UnaryMemberFunction mbfo1(&MemberFunctions::f); + mbfo1(a,2); + EXPECT_EQ(1,a.result); +} + +TEST(FunctionObjects,boundMemberFunctions) { + + MemberFunctions a; + BoundNullaryMemberFunction bmufo1(&MemberFunctions::e, a); + bmufo1(); + EXPECT_EQ(0,a.result); + + BoundUnaryMemberFunction bmbfo1(&MemberFunctions::f, a, 3); + bmbfo1(); + EXPECT_EQ(1,a.result); +} + +TEST(FunctionObjects,wrappers) { + + FunctionObject function_object; + NullaryFunctionCopy nfcopy(function_object); + nfcopy(); + // Can't really validate this baby. + +// std::cout << "Nullary Function References." << std::endl; + NullaryFunctionReference nfref(ref(function_object)); + nfref(); + // Can't really validate this baby. +} + +TEST(FunctionObjects,generators) { + + MemberFunctions a; + generateFunctionObject(rnf1)(); + EXPECT_EQ(0,free_result); + generateFunctionObject(ruf1)(3); + EXPECT_EQ(2,free_result); + generateFunctionObject(ruf1,3)(); + EXPECT_EQ(2,free_result); + generateFunctionObject(&MemberFunctions::e)(a); + EXPECT_EQ(0,a.result); + generateFunctionObject(&MemberFunctions::e, a)(); + EXPECT_EQ(0,a.result); + generateFunctionObject(&MemberFunctions::f)(a,1); + EXPECT_EQ(1,a.result); + generateFunctionObject(&MemberFunctions::h)(a,1); + EXPECT_EQ(3,a.result); + generateFunctionObject(&MemberFunctions::h,a,1)(); // Calls the non const version + EXPECT_EQ(3,a.result); + int j = 3; + generateFunctionObject(&MemberFunctions::h,a,j)(); // Calls the const version + EXPECT_EQ(3,a.result); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/parameters.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/test/parameters.cpp new file mode 100644 index 0000000..6528e20 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/parameters.cpp @@ -0,0 +1,128 @@ +/** + * @file /src/test/parameters.cpp + * + * @brief Unit Test for the @ref ecl::Parameter "Parameter" class. + * + * @date April 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/utilities/parameter.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** + * Classes + ****************************************************************************/ + +namespace ecl { +namespace utilities { +namespace tests { + + +class ParameterTest { +public: + ParameterTest() : value(3) {}; + Parameter value; +}; + +}}} + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::Parameter; +using ecl::utilities::tests::ParameterTest; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Parameter,get) { + + ParameterTest test; + int i1 = test.value(); + // int &i2 = test.value(); // This one is not permitted the class loses control of the variable. + const int i3 = test.value(); + const int &i4 = test.value(); + EXPECT_EQ(3,i1); + EXPECT_EQ(3,i3); + EXPECT_EQ(3,i4); +} + +TEST(Parameter,set) { + + ParameterTest test; + int i1 = test.value(); + int i_tmp = 3; + int &i2 = i_tmp; + const int i3 = test.value(); + const int &i4 = test.value(); + test.value(3); // temporary + EXPECT_EQ(3,test.value()); + test.value(i1); // int + EXPECT_EQ(3,test.value()); + test.value(i2); // int& + EXPECT_EQ(3,test.value()); + test.value(i3); // const int + EXPECT_EQ(3,test.value()); + test.value(i4); // const int& + EXPECT_EQ(3,test.value()); +} + +TEST(Parameter,assign) { + + ParameterTest test; + int i1 = test.value(); + int i_tmp = 3; + int &i2 = i_tmp; + const int i3 = test.value(); + const int &i4 = test.value(); + + test.value = 3; // temporary + EXPECT_EQ(3,test.value()); + test.value = i1; // int + EXPECT_EQ(3,test.value()); + test.value = i2; // int& + EXPECT_EQ(3,test.value()); + test.value = i3; // const int + EXPECT_EQ(3,test.value()); + test.value = i4; // const int& + EXPECT_EQ(3,test.value()); +} + +TEST(Parameter,eval) { + + ParameterTest test; + int i1; + i1 = test.value; + EXPECT_EQ(3,i1); +// int &i5 = test.value; // This one is not permitted the class loses control of the variable. + const int &i5 = test.value; + EXPECT_EQ(3,i5); + const int i6 = test.value; + EXPECT_EQ(3,i6); + i1 = i5; // remove the warning + EXPECT_EQ(3,i1); + i1 = i6; // remove the warning + EXPECT_EQ(3,i1); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/references.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/test/references.cpp new file mode 100644 index 0000000..b25b000 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/references.cpp @@ -0,0 +1,86 @@ +/** + * @file /src/test/references.cpp + * + * @brief Unit Test for reference wrappers and associated tools. + * + * @date July 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/utilities/references.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** +** Classes +*****************************************************************************/ + +namespace ecl { +namespace utilities { +namespace tests { + +class ReferenceDummy { +public: + int i; +}; + +}}} + +/***************************************************************************** +** Using +*****************************************************************************/ + +using ecl::ReferenceWrapper; +using ecl::cref; +using ecl::ref; +using ecl::is_reference_wrapper; +using ecl::utilities::tests::ReferenceDummy; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Reference,usage) { + + int i = 3; + ReferenceWrapper wrapper(i); + int &j = wrapper; + EXPECT_EQ(j,3); +} + +TEST(Reference,traits) { + // Workaround for undefined reference error. Why it happens if used + // directly in the gtest macros, I haven't root caused. + bool result1 = is_reference_wrapper< ReferenceWrapper >::value; + EXPECT_TRUE(result1); + bool result2 = is_reference_wrapper::value; + EXPECT_FALSE(result2); +} + +TEST(Reference,functions) { + int i = 3; + ReferenceWrapper refd = ref(i); + ReferenceWrapper crefd = cref(i); + EXPECT_EQ(3,refd); + EXPECT_EQ(3,crefd); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +/** + * @endcond + */ + diff --git a/ros2_ws/src/ecl_core/ecl_utilities/src/test/singleton.cpp b/ros2_ws/src/ecl_core/ecl_utilities/src/test/singleton.cpp new file mode 100644 index 0000000..1c535c4 --- /dev/null +++ b/ros2_ws/src/ecl_core/ecl_utilities/src/test/singleton.cpp @@ -0,0 +1,71 @@ +/** + * @file /src/test/singleton.cpp + * + * @brief Unit Test for the @ref ecl::Singleton "Singleton" class. + * + * @date April 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/utilities/singleton.hpp" + +/** + * @cond DO_NOT_DOXYGEN + */ + +/***************************************************************************** + * Classes + ****************************************************************************/ + +namespace ecl { +namespace utilities { +namespace tests { + +class TestSingleton : public ecl::Singleton { + + friend class ecl::Singleton; + + public: + int value() { return data; } + + protected: + TestSingleton() : data(32) {} + + private: + int data; +}; + +}}} + + +/***************************************************************************** +** Convenience Macro +*****************************************************************************/ + +#define TestInstance ecl::utilities::tests::TestSingleton::instance() + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Singleton,instantiation) { + int i = TestInstance.value(); + EXPECT_EQ(32,i); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + +/** + * @endcond + */ diff --git a/ros2_ws/src/ecl_lite b/ros2_ws/src/ecl_lite deleted file mode 160000 index f9b8aa0..0000000 --- a/ros2_ws/src/ecl_lite +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f9b8aa04c97ea332ae8ea7e052a31f7ec2670c9a diff --git a/ros2_ws/src/ecl_lite/.gitignore b/ros2_ws/src/ecl_lite/.gitignore new file mode 100644 index 0000000..620d3dc --- /dev/null +++ b/ros2_ws/src/ecl_lite/.gitignore @@ -0,0 +1,13 @@ +# Compiled Object files +*.slo +*.lo +*.o + +# Compiled Dynamic libraries +*.so +*.dylib + +# Compiled Static libraries +*.lai +*.la +*.a diff --git a/ros2_ws/src/ecl_lite/LICENSE b/ros2_ws/src/ecl_lite/LICENSE new file mode 100644 index 0000000..fb746f3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/LICENSE @@ -0,0 +1,32 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2022 Daniel Stonier +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + diff --git a/ros2_ws/src/ecl_lite/README.md b/ros2_ws/src/ecl_lite/README.md new file mode 100644 index 0000000..02a18eb --- /dev/null +++ b/ros2_ws/src/ecl_lite/README.md @@ -0,0 +1,16 @@ +ecl_lite +======== + +The ecl-lite stack includes packages with few dependencies on either system +or c++ functionality. This makes it ideal for very embedded builds where +many of the usual mechanisms are unavailable. + +* No malloc/new +* No exceptions +* Minimal templates + +It also includes a few packages which standardise lower level +api (e.g. posix/win32) with drop-ins to make them properly cross-platform, + +The development branch now uses ament. The most recent catkin based branches are on [release/0.61-indigo-kinetic](https://github.com/stonier/ecl_lite/tree/release/0.61-indigo-kinetic) and [release/0.61-melodic](https://github.com/stonier/ecl_lite/tree/release/0.61-melodic). + diff --git a/ros2_ws/src/ecl_lite/ecl_config/.cproject b/ros2_ws/src/ecl_lite/ecl_config/.cproject new file mode 100644 index 0000000..f193514 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/.cproject @@ -0,0 +1,712 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + + true + + true + + true + + + + + + make + + all + + true + + true + + true + + + + + + make + + tests + + true + + true + + true + + + + + + make + + test + + true + + true + + true + + + + + + make + + install + + true + + true + + true + + + + + + make + + + + utilities + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/.project b/ros2_ws/src/ecl_lite/ecl_config/.project new file mode 100644 index 0000000..6d9c0d3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/.project @@ -0,0 +1,78 @@ + + + ecl_config + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_config/.settings/language.settings.xml new file mode 100644 index 0000000..978c3d1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/.settings/language.settings.xml @@ -0,0 +1,4550 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_config/CHANGELOG.rst new file mode 100644 index 0000000..e31d0a5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/CHANGELOG.rst @@ -0,0 +1,16 @@ +========= +Changelog +========= + +0.61.4 (2016-01-10) +------------------- +* macro for use with checking for CXX11 + +0.61.3 (2016-01-06) +------------------- +* deprecation macro for clang. + +0.60.1 (2014-01-29) +------------------- +* update to catkin's CFG_EXTRAS for easy to find cmake modules. +* Contributors: Daniel Stonier diff --git a/ros2_ws/src/ecl_lite/ecl_config/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/CMakeLists.txt new file mode 100644 index 0000000..152e806 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/CMakeLists.txt @@ -0,0 +1,66 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_config) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include) + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() +ecl_detect_platform() + +############################################################################## +# Header Library Targets +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ + $ +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_package() + diff --git a/ros2_ws/src/ecl_lite/ecl_config/doxygen/changelog.dox b/ros2_ws/src/ecl_lite/ecl_config/doxygen/changelog.dox new file mode 100644 index 0000000..d38e75a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/doxygen/changelog.dox @@ -0,0 +1,22 @@ +/** + @page changelog ChangeLog + + + @section Changes + + - Mar 13 : msvc port. + - Nov 12 : catkinized. + - Mar 11 : added compile and runtime checks to detect the platform dependant typedef of char. + - Feb 11 : added a macro allowing for custom ecl configurations to be hand crafted. + - Feb 11 : new look, streamlined configuration (removed templates and improved macro detection). + - Sep 10 : Added macros to prevent inlining and mark deprecated code. + - Jul 10 : Added a platform class for determining characteristics of the platform (e.g. endianness). + - May 10 : Cmake win32 framework. + - Apr 10 : utilities for detecting fundamental type sizes and the level of posix on your system. + - Apr 09 : Integer and Float classes/typedefs/macros. + - Apr 09 : SizeOf convenience class (for compile time calculations). + - Apr 09 : Macros for platform capability definitions (defined in ecl.hpp). + + @section Bugs + +**/ diff --git a/ros2_ws/src/ecl_lite/ecl_config/doxygen/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_config/doxygen/mainpage.dox new file mode 100644 index 0000000..06035b0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/doxygen/mainpage.dox @@ -0,0 +1,178 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Different platforms have minor differences in their implementations. + Apart from the higher level api's such as threads and io devices, there + is also the platform's actual implementation of the c++ standard that + may differ from one machine to the next. For an instance, an int on a + DSP is not the same width as an int on an amd processor. Partly via the + cmake build process and partly via header referencing, the + config module's elements some checking + on the actual implementation for your system and define some + cross-platform @link Macros macros@endlink, + @link ecl types@endlink and + @link ecl classes@endlink that facilitate easy + handling of these fundamental properties. + +@section issues Cross Platform + + @subsection supportedPlatforms Major Platforms + + At the moment, the major implementations supported: + + - Posix + - Apple + - Win (partial) + + @subsection customPlatforms Custom Platforms + + It also has provision to supply details about custom (primarily wierd + embedded) platforms via the ECL_IS_CUSTOM macro. More detail below. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit that utilises the + configuration definitions and tools. + @code + #include + + // Functions + using ecl::is_big_endian; + using ecl::is_char_signed; + + // Types - refer to portable_types.hpp + using ecl::int8; + using ecl::uint8; + // ... + @endcode + +@section Usage + + @subsection cmakeConfig CMake Configuration + + CMake can do the hard yards on most platforms/toolchains and autodetect + what variables and headers can be used - this works mostly for the + main platforms as outlined above. The result of this guesswork are a + suite of @link Macros macros@endlink stored in the ecl/config/ecl.hpp + header. All macros are prefixed by an ECL, e.g. ECL_IS_POSIX. + + Note that other packages also do some platform detection to varying + degrees, e.g ecl_time_lite. The macros defined here are the most + general purpose macros only. + + @subsection customConfig Custom Configuration + + Alternatively, a header can be hand customised to tailor for your + own schwanky embedded board. To do this simply define the + ECL_IS_CUSTOM macro as pointing to a header somewhere on your system + before you call any ecl headers in your code. For example: + + @code + #define ECL_IS_CUSTOM + @endcode + + This will abort the cmake generated header and use your own hand crafted + header in its place. + + @subsection unknownConfiguration Unknown Configuration + + If your system is truly unknown, you can define the ECL_IS_UNKNOWN (set to 1) + macro before calling any other ecl headers. The ecl will then roughly try and + determine your system from whatever macros are defined by your compiler. + + This hasn't really been tested yet and probably will fall over horribly. + + @subsection MacrosSection Macros + + The following @ref Macros "macros" are the most important of those defined in this section. + + @code + // Platform macros - automatically detected by the build. + - ECL_IS_POSIX || ECL_IS_WIN32 || ECL_IS_APPLE || ECL_IS_CUSTOM + - ECL_HAS_POSIX_THREADS || ECL_HAS_WIN32_THREADS + - ECL_SIZE_OF_CHAR + - ECL_SIZE_OF_SHORT + - ECL_SIZE_OF_INT + - ECL_SIZE_OF_LONG + - ECL_SIZE_OF_LONG_LONG + - ECL_SIZE_OF_FLOAT + - ECL_SIZE_OF_DOUBLE + - ECL_SIZE_OF_LONG_DOUBLE + - ECL_CHAR_IS_SIGNED || ECL_CHAR_IS_UNSIGNED + - ECL_HAS_SHARED_LIBS || ECL_HAS_STATIC_LIBS + // ECL Development macros + - ECL_DISABLE_EXCEPTIONS + - ECL_DONT_INLINE + - ECL_DEPRECATED + - ECL_PUBLIC || ECL_LOCAL + @endcode + + Note that you may predefine ECL_HAS_SHARED_LIBS or ECL_HAS_STATIC_LIBS for your + project if both are available and you want to force appropriate behaviour + for the target set you are linking against. + + @subsection TypesSection Types + + When you absolutely need to specify the bit-width type you need to use, + the following typedefs are defined by the ECL when the appropriate types + are available. + + - @ref ecl::int8 "int8", @ref ecl::uint8 "uint8" + - @ref ecl::int16 "int16", @ref ecl::uint16 "uint16" + - @ref ecl::int32 "int32", @ref ecl::uint32 "uint32" + - @ref ecl::int64 "int64", @ref ecl::uint64 "uint64" + - @ref ecl::float32 "float32" + - @ref ecl::float64 "float64" + + The float96 and float128 types may or may not also be defined depending + on your platform. + + @subsection PlatformSniffers Platform Sniffers + + This is a set of functions that can be used to sniff your platform to determine + various characteristics. Checking for endianness: + + @code + // The function operates like a macro, and a good compiler will compile + // out the if mechanism and leave behind the required section of code. + if ( ecl::is_big_endian() { + // ... + else { + // ... + } + @endcode + + To check if your default char type is signed, or otherwise, use the following. + Note that this only works for runtime checks. To do compile time checks (for + use in template parameters etc), there is the ECL_CHAR_IS_SIGNED + and ECL_CHAR_IS_UNSIGNED macros. + @code + if ( ecl::is_char_signed() { + // ... + else { + // ... + } + @endcode + + +@section unitTests Unit Tests + + - src/test/endianness.cpp + - src/test/portable_types.cpp + +\section utilities Utilities + + Both utilities detect various properties on your system and send the data to stdout. Useful for + quick testing on embedded devices. + + - src/utilities/detect_endian.cpp : detects the endianness of your platform. + - src/utilities/detect_posix.cpp : detects the level of posix on your system. + +@section ChangeLog + + @ref changelog "ChangeLog" + +*/ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..e666bf4 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(config) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config.hpp new file mode 100644 index 0000000..71d25f2 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config.hpp @@ -0,0 +1,40 @@ +/** + * @file /include/ecl/config.hpp + * + * @brief Compiler and platform specific configurations. + * + * Collates all compiler and type configurations. Most of the + * implementation involves usage of macros and typedefs to manage + * the code in a standard way across platforms. + * + * @date April 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_HPP_ +#define ECL_CONFIG_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "config/macros.hpp" +#include "config/portable_types.hpp" +#include "config/endianness.hpp" +#include "config/char_sign.hpp" + +/***************************************************************************** + * Includes + ****************************************************************************/ + +#if defined(ECL_IS_WIN32) + #include "config/windows.hpp" +#elif defined(ECL_IS_POSIX) + #include +#endif + + +#endif /*ECL_CONFIG_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/.gitignore b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/.gitignore new file mode 100644 index 0000000..482e221 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/.gitignore @@ -0,0 +1 @@ +ecl.hpp diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/CMakeLists.txt new file mode 100644 index 0000000..a64bcfa --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/CMakeLists.txt @@ -0,0 +1,82 @@ +############################################################################### +# GENERATE HEADERS +# +# The cmake/project_generate_headers.cmake makes sure you have ecl.hpp built +# first. +############################################################################### + +################################### +# Platform +################################### + +IF(APPLE) + SET(ECL_IS_APPLE 1) +ENDIF() +IF(PLATFORM_IS_POSIX) + SET(ECL_IS_POSIX 1) +ENDIF() +IF(WIN32) + SET(ECL_IS_WIN32 1) +ENDIF() + +################################### +# Threads +################################### + +IF( ECL_PLATFORM_HAS_POSIX_THREADS ) + SET(ECL_HAS_POSIX_THREADS 1) +ELSEIF( ECL_PLATFORM_HAS_WIN32_THREADS ) + SET(ECL_HAS_WIN32_THREADS 1) +ENDIF() + +################################### +# TYPES +################################### + +SET(ECL_SIZE_OF_CHAR ${PLATFORM_SIZE_OF_CHAR}) +SET(ECL_SIZE_OF_SHORT ${PLATFORM_SIZE_OF_SHORT}) +SET(ECL_SIZE_OF_INT ${PLATFORM_SIZE_OF_INT}) +SET(ECL_SIZE_OF_LONG ${PLATFORM_SIZE_OF_LONG}) +SET(ECL_SIZE_OF_LONG_LONG ${PLATFORM_SIZE_OF_LONG_LONG}) +SET(ECL_SIZE_OF_FLOAT ${PLATFORM_SIZE_OF_FLOAT}) +SET(ECL_SIZE_OF_DOUBLE ${PLATFORM_SIZE_OF_DOUBLE}) +SET(ECL_SIZE_OF_LONG_DOUBLE ${PLATFORM_SIZE_OF_LONG_DOUBLE}) +IF( PLATFORM_IS_32_BIT ) + SET(ECL_IS_32_BIT 1) +ELSEIF( PLATFORM_IS_64_BIT ) + SET(ECL_IS_64_BIT 1) +ENDIF( PLATFORM_IS_32_BIT ) + +################################### +# Library type +################################### +if(BUILD_SHARED_LIBS) + set(ECL_HAS_SHARED_LIBS 1) +else() + set(ECL_HAS_STATIC_LIBS 1) +endif() + +############################################################################### +# GENERATE HEADER +############################################################################### + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/ecl.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/ecl.hpp) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ecl.hpp DESTINATION include/ecl/config) +install(FILES ${HEADERS} DESTINATION include/ecl/config) + +# If we want to supply the version number in major/minor/patch +# split version in parts and pass to extra file +#string(REPLACE "." ";" roscpp_VERSION_LIST "${roscpp_VERSION}") +#list(LENGTH roscpp_VERSION_LIST _count) +#if(NOT _count EQUAL 3) +# message(FATAL_ERROR "roscpp version '${roscpp_VERSION}' does not match 'MAJOR.MINOR.PATCH' pattern") +#endif() +#list(GET roscpp_VERSION_LIST 0 roscpp_VERSION_MAJOR) +#list(GET roscpp_VERSION_LIST 1 roscpp_VERSION_MINOR) +#list(GET roscpp_VERSION_LIST 2 roscpp_VERSION_PATCH) diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/char_sign.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/char_sign.hpp new file mode 100644 index 0000000..c54e134 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/char_sign.hpp @@ -0,0 +1,43 @@ +/** + * @file /ecl_config/include/ecl/config/char_sign.hpp + * + * @brief Tests in runtime to see if char is signed or not. + * + * @date March, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_CHAR_SIGN_HPP_ +#define ECL_CONFIG_CHAR_SIGN_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Determines if your platform char type is signed or otherwise. + * + * This is a useful runtime check, if you need a compile time check, ecl's + * cmake probling sets a macro in ecl/config/ecl.hpp. + * + * @return bool : true if signed, false otherwise. + */ +inline bool is_char_signed() { + + return ((CHAR_MIN == SCHAR_MIN) && (CHAR_MAX == SCHAR_MAX)); +} + + +} // namespace ecl + +#endif /* ECL_CONFIG_CHAR_SIGN_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl.hpp.in b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl.hpp.in new file mode 100644 index 0000000..7d5562e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl.hpp.in @@ -0,0 +1,163 @@ +/** + * @file /include/ecl/config/ecl.hpp + * + * @brief Pre-processed macro definitions that define the target platform. + * + * Cmake is used to check/verify your target platform parameters. The results + * of the platform check are defined here for use by the ecl in the form of + * preprocessed macros. + * + * Alternatively, a hand readied configuration file can be setup via the + * ECL_IS_CUSTOM macro. The use case for this generally applies when + * gathering source files (i.e. make 'source' target) ready to be used + * on a custom embedded board with its own toolchain/ide that are not + * usable with cmake. + * + * @date March 2009 + **/ +#ifndef ECL_CONFIG_MACROS_HPP_ +#define ECL_CONFIG_MACROS_HPP_ + +#define ECL_VERSION @ecl_config_VERSION@ + +/** + * @addtogroup Macros + * @{ +**/ +#if defined(ECL_IS_CUSTOM) // requires user to define something like: #define ECL_IS_CUSTOM + #include ECL_IS_CUSTOM +#elif defined(ECL_IS_UNKNOWN) // Ecl will try and guess without cmake's help. + #include "ecl_unknown.hpp" +#else // Let cmake help with the configuration. + /** + * @def ECL_IS_APPLE + * + * @brief Platform is an apple mac osx. + * + * Platform utilises the macosx system libraries. Note that + * this one is not exclusive with the others, usually + * both ECL_IS_POSIX and ECL_IS_APPLE will be set together. + * Other platforms: + * + * - ECL_IS_POSIX + * - ECL_IS_WIN32 + **/ + #cmakedefine ECL_IS_APPLE + /** + * @def ECL_IS_POSIX + * + * @brief Platform is posix-based. + * + * Platform is based on a variant of posix. Other platforms: + * + * - ECL_IS_WIN32 + * - ECL_IS_APPLE + **/ + #cmakedefine ECL_IS_POSIX + /** + * @def ECL_IS_WIN32 + * + * @brief Platform is a 32 bit windows OS. + * + * Platform utilises the win32 libraries. Other platforms: + * + * - ECL_IS_POSIX + * - ECL_IS_APPLE + **/ + #cmakedefine ECL_IS_WIN32 + /** + * @def ECL_HAS_POSIX_THREADS + * + * @brief Platform uses posix threads. + * + * Platform is using the posix thread model. Other thread models: + * + * - ECL_HAS_WIN32_THREADS + **/ + #cmakedefine ECL_HAS_POSIX_THREADS + /** + * @def ECL_HAS_WIN32_THREADS + * + * @brief Platform uses win32 threads. + * + * Platform is using the win32 thread model. Other thread models: + * + * - ECL_HAS_POSIX_THREADS + **/ + #cmakedefine ECL_HAS_WIN32_THREADS + /** + * @brief Defines the number of bytes for a char type. + */ + #cmakedefine ECL_SIZE_OF_CHAR @ECL_SIZE_OF_CHAR@ + /** + * @brief Defines the number of bytes for a short type. + */ + #cmakedefine ECL_SIZE_OF_SHORT @ECL_SIZE_OF_SHORT@ + /** + * @brief Defines the number of bytes for a int type. + */ + #cmakedefine ECL_SIZE_OF_INT @ECL_SIZE_OF_INT@ + /** + * @brief Defines the number of bytes for a long type. + **/ + #cmakedefine ECL_SIZE_OF_LONG @ECL_SIZE_OF_LONG@ + /** + * @brief Defines the number of bytes for a long long type. + **/ + #cmakedefine ECL_SIZE_OF_LONG_LONG @ECL_SIZE_OF_LONG_LONG@ + /** + * @brief Defines the number of bytes for a float type. + **/ + #cmakedefine ECL_SIZE_OF_FLOAT @ECL_SIZE_OF_FLOAT@ + /** + * @brief Defines the number of bytes for a double type. + **/ + #cmakedefine ECL_SIZE_OF_DOUBLE @ECL_SIZE_OF_DOUBLE@ + /** + * @brief Defines the number of bytes for a long double type. + **/ + #cmakedefine ECL_SIZE_OF_LONG_DOUBLE @ECL_SIZE_OF_LONG_DOUBLE@ + /** + * @brief Ecl exceptions are disabled. + * + * By default, ecl builds all its libraries with exceptions + * enabled. These can be disabled by passing + * -DECL_DISABLE_EXCEPTIONS:bool=true to cmake, or, if + * building in ros, setting this variable in + * $ROS_ROOT/rosconfig.cmake to be true. + **/ + #cmakedefine ECL_DISABLE_EXCEPTIONS + + /** + * @def ECL_HAS_SHARED_LIBS + * + * @brief Defined if ecl was built as shared libraries. + * + * If both shared and static ecl libs are present on the system, + * the user should predefine this if they wish to use ecl's shared + * libraries. + **/ + #if !defined(ECL_HAS_SHARED_LIBS) && !defined(ECL_HAS_STATIC_LIBS) + #cmakedefine ECL_HAS_SHARED_LIBS @ECL_HAS_SHARED_LIBS@ + #endif + /** + * @def ECL_HAS_STATIC_LIBS + * + * @brief Defined if ecl was built as static libraries. + * + * If both shared and static ecl libs are present on the system, + * the user should predefine this if they wish to use ecl's static + * libraries. + **/ + #if !defined(ECL_HAS_SHARED_LIBS) && !defined(ECL_HAS_STATIC_LIBS) + #cmakedefine ECL_HAS_STATIC_LIBS @ECL_HAS_STATIC_LIBS@ + #endif + +#endif + +/** + * @} + **/ + +#endif /* ECL_CONFIG_MACROS_HPP_ */ + diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl_unknown.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl_unknown.hpp new file mode 100644 index 0000000..3a9b71e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/ecl_unknown.hpp @@ -0,0 +1,110 @@ +/** + * @file /ecl_config/include/ecl/config/ecl_unknown.hpp + * + * @brief Guesswork to determine parameters from macros only. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_UNKNOWN_HPP_ +#define ECL_CONFIG_UNKNOWN_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Integers +*****************************************************************************/ + +/* + * The c99 standard will only define certain macros for c++ + * if explicitly requested. + */ +#define __STDC_LIMIT_MACROS + +#if defined(__GNUC__) + /* + * Note that cstdint is not enabled by default by gcc yet (v4.4). It will + * give a compile time error unless you explicitly pass -std=c++0x to gcc. + */ + #if __GXX_EXPERIMENTAL_CXX0X__ > 0 + #include + #else + #include + #endif +#elif (defined(__STDC__) && __STDC__) + #include +#else + // nothing here yet - look in graveyard/include/portable_integers for some ideas. +#endif + +/* + * These are very naive - update these as we come across different platforms. + */ +#if CHAR_MAX == INT8_MAX + #define ECL_SIZE_OF_CHAR 1 +#else + #error "ECL_SIZE_OF_CHAR could not be determined (probably faulty ecl logic)." +#endif +#if SHRT_MAX == INT16_MAX + #define ECL_SIZE_OF_SHORT 2 +#else + #error "ECL_SIZE_OF_SHORT could not be determined (probably faulty ecl logic)." +#endif +#if INT_MAX == INT32_MAX + #define ECL_SIZE_OF_INT 4 +#else + #error "ECL_SIZE_OF_INT could not be determined (probably faulty ecl logic)." +#endif +#if LONG_MAX == INT32_MAX + #define ECL_SIZE_OF_LONG 4 +#elif LONG_MAX == INT64_MAX + #define ECL_SIZE_OF_LONG 8 +#else + #error "ECL_SIZE_OF_LONG could not be determined (probably faulty ecl logic)." +#endif + +#if LONG_LONG_MAX == INT64_MAX + #define ECL_SIZE_OF_LONG_LONG 8 +#else + #error "ECL_SIZE_OF_LONG_LONG could not be determined (probably faulty ecl logic)." +#endif + +/***************************************************************************** +** Floats +*****************************************************************************/ +/* + * These may be somewhat naively assumed. I should hand craftfor + * particular platforms in the future if it ever really + * differs. + */ +#ifdef __GNUC__ + #ifdef __SIZEOF_FLOAT__ + #define ECL_SIZE_OF_FLOAT __SIZEOF_FLOAT__ + #else + #define ECL_SIZE_OF_FLOAT 4 + #endif + #ifdef __SIZEOF_DOUBLE__ + #define ECL_SIZE_OF_DOUBLE __SIZEOF_DOUBLE__ + #else + #define ECL_SIZE_OF_DOUBLE 8 + #endif + #ifdef __SIZEOF_LONG_DOUBLE__ + #define ECL_SIZE_OF_LONG_DOUBLE __SIZEOF_LONG_DOUBLE__ + #else + #define ECL_SIZE_OF_LONG_DOUBLE 16 + #endif +#else // Non Gnu platforms + #define ECL_SIZE_OF_FLOAT 4 + #define ECL_SIZE_OF_DOUBLE 8 + #define ECL_SIZE_OF_LONG_DOUBLE 16 // This is often 12! +#endif + +#endif /* ECL_CONFIG_UNKNOWN_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/endianness.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/endianness.hpp new file mode 100644 index 0000000..2e7e447 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/endianness.hpp @@ -0,0 +1,49 @@ +/** + * @file /ecl_config/include/ecl/config/endianness.hpp + * + * @brief Determines the endianness of the platform. + * + * @date July, 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_ENDIANNESS_HPP_ +#define ECL_CONFIG_ENDIANNESS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "portable_types.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + /** + * @brief Determines if your platform is big endian (at compile time). + * + * This is a nice function that I found on stack overflow - the best + * thing about it, is that a good compiler will see that its a const + * function and thus store it in your program as a constant as well + * as excluding any code that fails this test (within the usual if/else + * condition check). Thus, effectively giving it the same power as + * a macro. Brilliant! + * + * @return bool : true if big endian, false otherwise. + */ + inline bool is_big_endian() { + union { + uint32 i; + char c[4]; + } bint = {0x01020304}; + + return bint.c[0] == 1; + } + +} // namespace ecl + +#endif /* ECL_CONFIG_ENDIANNESS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/macros.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/macros.hpp new file mode 100644 index 0000000..2b1a797 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/macros.hpp @@ -0,0 +1,201 @@ +/** + * @file /ecl_config/include/ecl/config/macros.hpp + * + * @brief Various macros useful for development. + * + * @date September 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_UTILITY_MACROS_HPP_ +#define ECL_CONFIG_UTILITY_MACROS_HPP_ + +/***************************************************************************** +** Include +*****************************************************************************/ + +#include + +/***************************************************************************** +** Macros +*****************************************************************************/ +/** + * @addtogroup Macros + * @{ +**/ + +/** + * @brief Prevents a function from being inlined. + * + * The following macro prevents functions from being inlined by both + * gnu or msvc compilers. + * + * @code + * ELC_DONT_INLINE void f() { std::cout << "Dude" << std::endl; } + * @endcode +**/ +#if (defined __GNUC__) + #define ECL_DONT_INLINE __attribute__((noinline)) +#elif (defined _MSC_VER) + #define ECL_DONT_INLINE __declspec(noinline) +#else + #define ECL_DONT_INLINE +#endif + +/** + * @brief C++11 support is available. + * + * This is a very dodgy way of checking - haven't tested across compilers + * very well, and it doesn't take into account the partial completeness + * of the implementations. + * + * It does however, provide a way for headers to use c++11 symbols + * in a non-destructive way for users (we often define typedefs for + * shared ptr variations). + */ +#if defined(__cplusplus) && (__cplusplus >= 201103L) + #define ECL_CXX11_FOUND +#else + #define ECL_CXX11_NOT_FOUND +#endif + +/***************************************************************************** +** Depracated +*****************************************************************************/ + +/** + * @brief Deprecated compiler warnings. + * + * The following macro emits deprecated compiler warnings by both + * gnu or msvc compilers. + * + * @code + * ECL_DEPRECATED void f() { std::cout << "Dude" << std::endl; } + * @endcode +**/ +#if (defined __GNUC__) + #define ECL_DEPRECATED __attribute__((deprecated)) +#elif (defined _MSC_VER) + #define ECL_DEPRECATED __declspec(deprecated) +#elif defined(__clang__) + #define ECL_DEPRECATED __attribute__((deprecated("Use of this method is deprecated"))) +#else + #define ECL_DEPRECATED +#endif + +/***************************************************************************** +** Unused +*****************************************************************************/ + +/** + * @brief Attribute unused. + * + * Indicates a variable, type, function is unused to avoid warning checks. + * + * @code + * // for types + * typename this_foo ECL_UNUSED other_foo; + * // in method arguments + * int foo (ECL_UNUSED int bar) { + * return 0; + * } + * @endcode +**/ +#if (defined __GNUC__) || defined (__clang__) + #define ECL_UNUSED __attribute__ ((unused)) +#else + #define ECL_UNUSED +#endif + +/** + * @} + **/ + +/***************************************************************************** +** Visibility +*****************************************************************************/ + +/** + * @def ECL_HELPER_LOCAL + * @sa ECL_HELPER_EXPORT, ECL_HELPER_IMPORT +**/ +/** + * @def ECL_HELPER_IMPORT + * @sa ECL_HELPER_EXPORT, ECL_HELPER_LOCAL +**/ +/** + * @def ECL_HELPER_EXPORT + * + * @brief Declare public visibility for libraries. + * + * This emits (in a cross platform way) the required symbols + * for setting whether a function/class should be visible or + * hidden. Note only does this protect the private parts + * of your library, but it can also greatly speed up the + * linking process. + * + * - http://gcc.gnu.org/wiki/Visibility + * + * To check what symbols are being exported for a gnu library, + * + * @code + * nm -C -D .so + * @endcode + * + * Usage: + * + * Each package needs to create it's own macro to make use of + * the macro that cmake defines for library targets: + * + * @code + * #ifdef ROS_BUILD_SHARED_LIBS // ros is being built around shared libraries + * #ifdef ecl_common_EXPORTS // we are building a shared lib/dll + * #define ecl_common_PUBLIC ROS_HELPER_EXPORT + * #else // we are using shared lib/dll + * #define ecl_common_PUBLIC ROS_HELPER_IMPORT + * #endif + * #else // ros is being built around static libraries + * #define ecl_common_DECL + * #endif + * @endcode + * + * And use it alongside class or function definitions: + * + * @code + * extern "C" ecl_common_PUBLIC void function(int a); + * class ecl_common_PUBLIC SomeClass { + * int c; + * ecl_common_LOCAL void privateMethod(); // Only for use within this DSO + * public: + * Person(int _c) : c(_c) { } + * static void foo(int a); + * }; + * @endcode + * + * @sa ECL_HELPER_IMPORT, ECL_HELPER_LOCAL +**/ + +#if defined(ECL_IS_WIN32) || defined(ECL_IS_CYGWIN) + #define ECL_HELPER_IMPORT __declspec(dllimport) + #define ECL_HELPER_EXPORT __declspec(dllexport) + #define ECL_HELPER_LOCAL +#else + #if defined(ECL_IS_POSIX) && __GNUC__ >= 4 + #define ECL_HELPER_IMPORT __attribute__ ((visibility("default"))) + #define ECL_HELPER_EXPORT __attribute__ ((visibility("default"))) + #define ECL_HELPER_LOCAL __attribute__ ((visibility("hidden"))) + #else + #define ECL_HELPER_IMPORT + #define ECL_HELPER_EXPORT + #define ECL_HELPER_LOCAL + #endif +#endif + +// Until we depracate this entirely, need this to avoid being interpreted as a variable +#define ECL_PUBLIC +#define ECL_LOCAL + + +#endif /* ECL_UTILITY_CONFIG_MACROS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/portable_types.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/portable_types.hpp new file mode 100644 index 0000000..89e59dc --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/portable_types.hpp @@ -0,0 +1,91 @@ +/** + * @file /ecl_config/include/ecl/config/portable_types.hpp + * + * @brief Type definitions for integer types. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_PORTABLE_TYPES_HPP_ +#define ECL_PORTABLE_TYPES_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Integers +*****************************************************************************/ +// If errors show up, need to check the ecl macro logic. +#if ECL_SIZE_OF_CHAR == 1 + typedef char int8; /**< @brief An alias for the platform's 8 bit integer type. **/ + typedef unsigned char uint8; /**< @brief An alias for the platform's unsigned 8 bit integer type. **/ +#else + #error "ecl::int8 could not be typedef'd (probably faulty ecl logic)." +#endif + +#if ECL_SIZE_OF_SHORT == 2 + typedef short int16; /**< @brief An alias for the platform's 16 bit integer type. **/ + typedef unsigned short uint16; /**< @brief An alias for the platform's unsigned 16 bit integer type. **/ +#else + #error "ecl::int16 could not be typedef'd (probably faulty ecl logic)." +#endif + +#if ECL_SIZE_OF_INT == 4 + typedef int int32; /**< @brief An alias for the platform's 32 bit integer type. **/ + typedef unsigned int uint32; /**< @brief An alias for the platform's unsigned 32 bit integer type. **/ +#else + #error "ecl::int32 could not be typedef'd (probably faulty ecl logic)." +#endif + +#if ECL_SIZE_OF_LONG == 4 + typedef long long int64; /**< @brief An alias for the platform's 64 bit integer type. **/ + typedef unsigned long long uint64; /**< @brief An alias for the platform's unsigned 64 bit integer type. **/ +#elif ECL_SIZE_OF_LONG == 8 + typedef long int64; /**< @brief An alias for the platform's 64 bit integer type. **/ + typedef unsigned long uint64; /**< @brief An alias for the platform's unsigned 64 bit integer type. **/ +#else + #error "ecl::int64 could not be typedef'd (probably faulty ecl logic)." +#endif + +/***************************************************************************** +** Floats +*****************************************************************************/ + +#if ECL_SIZE_OF_FLOAT == 4 + typedef float float32; /**< @brief An alias for the platform's 32 bit float type. **/ +#else + #error "ecl::float32 could not be typedef'd (probably faulty ecl logic)." +#endif +#if ECL_SIZE_OF_DOUBLE == 8 + typedef double float64; /**< @brief An alias for the platform's 64 bit float type. **/ +#elif ECL_SIZE_OF_LONG_DOUBLE == 8 + typedef long double float64; /**< @brief An alias for the platform's 64 bit float type. **/ +#else + #error "ecl::float64 could not be typedef'd (probably faulty ecl logic)." +#endif +#if ECL_SIZE_OF_LONG_DOUBLE == 12 + typedef long double float96; /**< @brief An alias for the platform's 96 bit float type. **/ +#elif ECL_SIZE_OF_LONG_DOUBLE == 16 + typedef long double float128; /**< @brief An alias for the platform's 128 bit float type. **/ +#else + #define ECL_LONG_DOUBLE_UNDEFINED + #define ECL_LONG_LONG_DOUBLE_UNDEFINED + //#error "ecl::float96 could not be typedef'd (probably faulty ecl logic)." +#endif + +} // namespace ecl + +#endif /* ECL_PORTABLE_TYPES_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/windows.hpp b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/windows.hpp new file mode 100644 index 0000000..30f9e39 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/include/ecl/config/windows.hpp @@ -0,0 +1,39 @@ +/** + * @file /ecl_config/include/ecl/config/windows.hpp + * + * @brief Custom setup for windoze. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONFIG_WINDOWS_HPP_ +#define ECL_CONFIG_WINDOWS_HPP_ + +/***************************************************************************** +** Win32 +*****************************************************************************/ + +#include + +#if defined(ECL_IS_WIN32) + #define _WINSOCKAPI_ // stops windows.h including winsock.h (we use winsock2) + #include + #ifdef min + #undef min + #endif + #ifdef max + #undef max + #endif + + #ifdef _MSC_VER + #pragma warning(disable: 4251) // Disable warnings about import/exports when deriving from std classes + #pragma warning(disable: 4275) // "" + #pragma warning (disable:4996) // Disable warnings about deprecated ctime + #pragma warning (disable:4290) // Disable warnings about unsupported c++ exception specifications + #endif +#endif + +#endif /* ECL_CONFIG_WINDOWS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_config/package.xml b/ros2_ws/src/ecl_lite/ecl_config/package.xml new file mode 100644 index 0000000..102dce5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/package.xml @@ -0,0 +1,30 @@ + + + ecl_config + 1.2.0 + + These tools inspect and describe your system with macros, types + and functions. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_config + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_build + ecl_license + ecl_license + ecl_build + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/src/CMakeLists.txt new file mode 100644 index 0000000..76d69b6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/CMakeLists.txt @@ -0,0 +1,10 @@ +############################################################################### +# Subdirectories +############################################################################### + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() +add_subdirectory(utilities) diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/test/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/src/test/CMakeLists.txt new file mode 100644 index 0000000..ff66734 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/test/CMakeLists.txt @@ -0,0 +1,20 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_config_add_gtest test_name) + ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp) + # If we don't have gtest installed, then the target doesn't get made - check! + if(TARGET ecl_test_${test_name}) + target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME}) + endif() +endmacro() + +############################################################################### +# Tests +############################################################################### + +ecl_config_add_gtest(char_sign) +ecl_config_add_gtest(endianness) +ecl_config_add_gtest(macros) +ecl_config_add_gtest(portable_types) diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/test/char_sign.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/test/char_sign.cpp new file mode 100644 index 0000000..8902d3e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/test/char_sign.cpp @@ -0,0 +1,45 @@ +/** + * @file /ecl_config/src/test/char_sign.cpp + * + * @brief Unit test for char sign check. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/config/char_sign.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ +/* + * Doesn't matter what the result is, just provide coverage. + * compile time if they aren't. + */ +TEST(TypeTests,fundamentals) { + bool result = ecl::is_char_signed(); + if ( result ) { + std::cout << "Char is signed." << std::endl; + } else { + std::cout << "Char is unsigned." << std::endl; + } + result = false; // stop gcc warnings. + SUCCEED(); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + std::cout << "CHAR_MIN" << CHAR_MIN << std::endl; + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/test/endianness.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/test/endianness.cpp new file mode 100644 index 0000000..7d98c94 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/test/endianness.cpp @@ -0,0 +1,40 @@ +/** + * @file /ecl_config/src/test/endianness.cpp + * + * @brief Unit test for endianness. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/config/endianness.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ +/* + * Doesn't matter what the result is, just provide coverage. + * compile time if they aren't. + */ +TEST(TypeTests,fundamentals) { + bool result = ecl::is_big_endian(); + (void)result; + result = false; + SUCCEED(); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/test/macros.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/test/macros.cpp new file mode 100644 index 0000000..ccfa1d0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/test/macros.cpp @@ -0,0 +1,35 @@ +/** + * @file /ecl_config/src/test/char_sign.cpp + * + * @brief Tests for ecl macros + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/config/macros.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(Macros, unused) { + // without ECL_UNUSED, with the current project settings, this should cause + // 'error: typedef 'foo' locally defined but not used on at least gcc + typedef int ECL_UNUSED foo; + SUCCEED(); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/test/portable_types.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/test/portable_types.cpp new file mode 100644 index 0000000..2870fd7 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/test/portable_types.cpp @@ -0,0 +1,52 @@ +/** + * @file /ecl_config/src/test/portable_types.cpp + * + * @brief Unit test for the portable types. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/config/endianness.hpp" + +/***************************************************************************** +** Tests +*****************************************************************************/ +/* + * Just make sure these are all defined. It will fail with an #error at + * compile time if they aren't. + */ +TEST(TypeTests,fundamentals) { + ecl::int8 i8 = 1; i8 = 2; (void)i8; + ecl::uint8 ui8 = 1; ui8 = 2; (void)ui8; + ecl::int8 i16 = 1; i16 = 2; (void)i16; + ecl::uint8 ui16 = 1; ui16 = 2; (void)ui16; + ecl::int8 i32 = 1; i32 = 2; (void)i32; + ecl::uint8 ui32 = 1; ui32 = 2; (void)ui32; + ecl::int8 i64 = 1; i64 = 1; (void)i64; + ecl::uint8 ui64 = 1; ui64 = 2; (void)ui64; + ecl::float32 f32 = 1.0; f32 = 2.0; (void)f32; + ecl::float64 f64 = 1.0; f64 = 2.0; (void)f64; + #if ECL_SIZE_OF_LONG_DOUBLE == 12 + ecl::float96 f96 = 1.0; f96 = 2.0; (void)f96; + #elif ECL_SIZE_OF_LONG_DOUBLE == 16 + ecl::float128 f128 = 1.0; f128 = 2.0; (void)f128; + #endif + SUCCEED(); +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} + + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/utilities/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/CMakeLists.txt new file mode 100644 index 0000000..88fc421 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/CMakeLists.txt @@ -0,0 +1,16 @@ +############################################################################### +# SETUP +############################################################################### + +add_executable(ecl_detect_endian detect_endian.cpp) +target_link_libraries(ecl_detect_endian ${PROJECT_NAME}) +set_target_properties(ecl_detect_endian PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) +install(TARGETS ecl_detect_endian RUNTIME DESTINATION bin) + +if(NOT MSVC) + add_executable(ecl_detect_posix detect_posix.cpp) + target_link_libraries(ecl_detect_posix ${PROJECT_NAME}) + set_target_properties(ecl_detect_posix PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) + install(TARGETS ecl_detect_posix RUNTIME DESTINATION bin) +endif() + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_endian.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_endian.cpp new file mode 100644 index 0000000..12e2e5b --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_endian.cpp @@ -0,0 +1,29 @@ +/** + * @file src/utilities/detect_endian.cpp + * + * @brief Simple utility used to detect endianness. + * + * @date Jul 10, 2010 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/config/endianness.hpp" + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /* argc */, char** /* argv */) { + + if ( ecl::is_big_endian() ) { + std::cout << "Platform is big endian." << std::endl; + } else { + std::cout << "Platform is little endian." << std::endl; + } + return 0; +} + diff --git a/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_posix.cpp b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_posix.cpp new file mode 100644 index 0000000..eb8c9df --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_config/src/utilities/detect_posix.cpp @@ -0,0 +1,747 @@ +/** + * @file src/utilities/detect_posix.cpp + * + * @brief Detects the posix functionality available on this platform. + * + * Does a series of macro checks to determine the level of posix + * functionality that is available on this platform. + * + * @date May, 2009. + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Preprocessing +*****************************************************************************/ + +#ifdef __GNUC__ + #include + #include +#endif + +/***************************************************************************** +** Main +*****************************************************************************/ + + +int main() +{ +#ifndef _POSIX_VERSION + printf("No support for POSIX on this system!\n"); +#else //see what POSIX version + long val; + int errno; + + #if defined(POSIX_VERSION) + printf("POSIX_VERSION = %d.\n",_POSIX_VERSION); + #endif + #if defined(POSIX2_VERSION) + printf("POSIX2_VERSION = %d.\n",_POSIX2_VERSION); + #endif + #if defined(POSIX2_C_VERSION) + printf("POSIX2_C_VERSION = %d.\n",_POSIX2_C_VERSION); + #endif + #if _POSIX_VERSION == 199009 + printf("This system supports POSIX.1 without support for POSIX.4.\n"); + #else + #if _POSIX_VERSION >= 199309 + printf ("This system has Posix Version %ld. \n", _POSIX_VERSION); + printf ("POSIX.1 and POSIX.4 are both supported. \n"); + #else + printf("This system supports a strange POSIX version between 199009 and 199309.\n"); + #endif + //DO POSIX.4 tests + printf ("POSIX.4 Options Test Results:\n"); + #ifdef _POSIX_REALTIME_SIGNALS + printf(" POSIX.4 Additional real time signals are supported.\n"); + #ifdef _POSIX_RTSIG_MAX + printf(" _POSIX_RTSIG_MAX=%d Max real time signals.\n",_POSIX_RTSIG_MAX); + #else + printf(" No _POSIX_RTSIG_MAX value exists.\n"); + #endif + #ifdef _POSIX_SIGQUEUE_MAX + printf(" _POSIX_SIGQUEUE_MAX=%d Max real time signals at once per process.\n",_POSIX_SIGQUEUE_MAX); + #else + printf(" No _POSIX_SIGQUEUE_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Additional real time signals are not supported.\n"); + #endif + #ifdef _POSIX_PRIORITY_SCHEDULING + printf(" POSIX.4 Priority scheduling is supported.\n"); + #else + printf(" POSIX.4 Priority scheduling is not supported.\n"); + #endif + #ifdef _POSIX_TIMERS + printf(" POSIX.4 Clocks and timers are supported.\n"); + #ifdef _POSIX_TIMER_MAX + printf(" _POSIX_TIMER_MAX=%d Max number of concurrent timers a process can have.\n",_POSIX_TIMER_MAX); + #else + printf(" No _POSIX_TIMER_MAX value exists.\n"); + #endif + #ifdef _POSIX_DELAYTIMER_MAX + printf(" _POSIX_DELAYTIMER_MAX=%d Max number of times a timer can have a detectable overrun.\n",_POSIX_DELAYTIMER_MAX); + #else + printf(" No _POSIX_DELAYTIMER_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Clocks and timers are not supported.\n"); + #endif + #ifdef _POSIX_ASYNCHRONOUS_IO + printf(" POSIX.4 Asynchronous I/O is supported.\n"); + #ifdef _POSIX_AIO_LISTIO_MAX + printf(" _POSIX_AIO_LISTIO_MAX=%d Max operations in one call\n",_POSIX_AIO_LISTIO_MAX); + #else + printf(" No _POSIX_AIO_LISTIO_MAX value exists.\n"); + #endif + #ifdef _POSIX_AIO_MAX + printf(" _POSIX_AIO_MAX=%d Max concurrent Async I/Os\n",_POSIX_AIO_MAX); + #else + printf(" No _POSIX_AIO_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Asynchronous I/O is not supported.\n"); + #endif + #ifdef _POSIX_SYNCHRONIZED_IO //Only supported if Asynchronous I/O is supported + printf(" POSIX.4 Synchronized I/O is supported.\n"); + #else + printf(" POSIX.4 Synchronized I/O is not supported.\n"); + #endif + #ifdef _POSIX_PRIORITIZED_IO + printf(" POSIX.4 Prioritized asynchronous I/O is supported.\n"); + #ifdef _POSIX_AIO_PRIO_DELTA_MAX + printf(" _POSIX_AIO_PRIO_DELTA_MAX=%d Max amount AIO priority can be decreased.\n",_POSIX_AIO_PRIO_DELTA_MAX); + #else + printf(" No _POSIX_AIO_PRIO_DELTA_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Prioritized asynchronous I/O is not supported.\n"); + #endif + #ifdef _POSIX_FSYNC + printf(" POSIX.4 The fsync function is supported.\n"); + #else + printf(" POSIX.4 The fsync function is not supported.\n"); + #endif + #ifdef _POSIX_MAPPED_FILES + printf(" POSIX.4 Mapping files as memory is supported.\n"); + #else + printf(" POSIX.4 Mapping files as memory is not supported.\n"); + #endif + #ifdef _POSIX_MEMLOCK + printf(" POSIX.4 Locking memory is supported.\n"); + #else + printf(" POSIX.4 Locking memory is not supported.\n"); + #endif + #ifdef _POSIX_MEMLOCK_RANGE + printf(" POSIX.4 Locking memory ranges is supported.\n"); + #else + printf(" POSIX.4 Locking memory ranges is not supported.\n"); + #endif + #ifdef _POSIX_MEMORY_PROTECTION + printf(" POSIX.4 Setting memory protection is supported.\n"); + #else + printf(" POSIX.4 Setting memory protection is not supported.\n"); + #endif + #ifdef _POSIX_MESSAGE_PASSING + printf(" POSIX.4 Message Queues are supported.\n"); + #ifdef _POSIX_MQ_OPEN_MAX + printf(" _POSIX_MQ_OPEN_MAX=%d Max # of message queues per process.\n",_POSIX_MQ_OPEN_MAX); + #else + printf(" No _POSIX_MQ_OPEN_MAX value exists.\n"); + #endif + #ifdef _POSIX_MQ_PRIO_MAX + printf(" _POSIX_MQ_PRIO_MAX=%d Max # of message priorities.\n",_POSIX_MQ_PRIO_MAX); + #else + printf(" No _POSIX_MQ_PRIO_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Message Queues are not supported.\n"); + #endif + #ifdef _POSIX_SEMAPHORES + printf(" POSIX.4 Semaphores are supported.\n"); + #ifdef _POSIX_SEM_NSEMS_MAX + printf(" _POSIX_SEM_NSEMS_MAX=%d Max # of open semaphores per process.\n",_POSIX_SEM_NSEMS_MAX); + #else + printf(" No _POSIX_SEM_NSEMS_MAX value exists.\n"); + #endif + #ifdef _POSIX_SEM_VALUE_MAX + printf(" _POSIX_SEM_VALUE_MAX=%d Maximum semaphore value.\n",_POSIX_SEM_VALUE_MAX); + #else + printf(" No _POSIX_SEM_VALUE_MAX value exists.\n"); + #endif + #else + printf(" POSIX.4 Semaphores are not supported.\n"); + #endif + #ifdef _POSIX_SHARED_MEMORY_OBJECTS + printf(" POSIX.4 Shared memory objects are supported.\n"); + #else + printf(" POSIX.4 Shared memory objects are not supported.\n"); + #endif + + #ifdef _POSIX_THREADS + printf(" POSIX.1c pthreads are supported.\n"); + #else + printf(" POSIX.1c pthreads are not supported.\n"); + #endif + #ifdef _POSIX_THREAD_ATTR_STACKADDRTHREAD_ATTR_STACKADDR + printf(" POSIX.4 Thread stack address attribute option is supported.\n"); + #else + printf(" POSIX.4 Thread stack address attribute option is not supported.\n"); + #endif + #ifdef _POSIX_THREAD_ATTR_STACKSIZE + printf(" POSIX.4 Thread stack size attribute option is supported.\n"); + #else + printf(" POSIX.4 Thread stack size attribute option is not supported.\n"); + #endif + #ifdef _POSIX_THREAD_SAFE_FUNCTIONS + printf(" POSIX.4 Thread-safe functions are supported.\n"); + #else + printf(" POSIX.4 Thread-safe functions are not supported.\n"); + #endif + #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING + printf(" POSIX.1c thread execution scheduling is supported.\n"); + #else + printf(" POSIX.1c thread execution scheduling is not supported.\n"); + #endif + #ifdef _POSIX_THREAD_PRIO_INHERIT + printf(" POSIX.4 Thread priority inheritance option is supported.\n"); + #else + printf(" POSIX.4 Thread priority inheritance option is not supported.\n"); + #endif + #ifdef _POSIX_THREAD_PROCESS_SHARED + printf(" POSIX.4 Process-shared synchronization is supported.\n"); + #else + printf(" POSIX.4 Process-shared synchronization is not supported.\n"); + #endif + #ifdef _POSIX_POSIX_PII + printf(" Protocol-independent interfaces are supported.\n"); + #else + printf(" Protocol-independent interfaces are not supported.\n"); + #endif + #ifdef _POSIX_PII_XTI + printf(" XTI protocol-indep. interfaces are supported.\n"); + #else + printf(" XTI protocol-indep. interfaces are not supported.\n"); + #endif + #ifdef _POSIX_PII_SOCKET + printf(" Socket protocol-indep. interfaces are supported.\n"); + #else + printf(" Socket protocol-indep. interfaces are not supported.\n"); + #endif + #ifdef _POSIX_PII_INTERNET + printf(" Internet family of protocols is supported.\n"); + #else + printf(" Internet family of protocols is not supported.\n"); + #endif + #ifdef _POSIX_PII_INTERNET_STREAM + printf(" Connection-mode Internet protocol is supported.\n"); + #else + printf(" Connection-mode Internet protocol is not supported.\n"); + #endif + #ifdef _POSIX_PII_INTERNET_DGRAM + printf(" Connectionless Internet protocol is supported.\n"); + #else + printf(" Connectionless Internet protocol is not supported.\n"); + #endif + #ifdef _POSIX_PII_OSI + printf(" ISO/OSI family of protocols is supported.\n"); + #else + printf(" ISO/OSI family of protocols is not supported.\n"); + #endif + #ifdef _POSIX_PII_OSI_COTS + printf(" Connection-mode ISO/OSI service is supported.\n"); + #else + printf(" Connection-mode ISO/OSI service is not supported.\n"); + #endif + #ifdef _POSIX_PII_OSI_CLTS + printf(" Connectionless ISO/OSI service is supported.\n"); + #else + printf(" Connectionless ISO/OSI service is not supported.\n"); + #endif + #ifdef _POSIX_POLL + printf(" Implementation supports `poll' function.\n"); + #else + printf(" poll function is not supported.\n"); + #endif + #ifdef _POSIX_SELECT + printf(" Implementation supports `select' and `pselect'.\n"); + #else + printf(" Implementation does not support `select' and `pselect'.\n"); + #endif + #ifdef _XOPEN_REALTIME + printf(" X/Open realtime support is available.\n"); + #else + printf(" X/Open realtime support is not available..\n"); + #endif + #ifdef _XOPEN_REALTIME_THREADS + printf(" X/Open realtime thread support is available.\n"); + #else + printf(" X/Open realtime thread support is not available.\n"); + #endif + #ifdef _XOPEN_SHM + printf(" XPG4.2 Shared memory interface is supported.\n"); + #else + printf(" XPG4.2 Shared memory interface is not supported.\n"); + #endif + #ifdef _XBS5_ILP32_OFF32 + printf(" 32-bit int, long, pointer, and off_t types are supported.\n"); + #else + printf(" 32-bit int, long, pointer, and off_t types are not supported.\n"); + #endif + #ifdef _XBS5_ILP32_OFFBIG + printf(" 32-bit int, long, and pointer and off_t with at least 64 bits is supported.\n"); + #else + printf(" 32-bit int, long, and pointer and off_t with at least 64 bits is not supported.\n"); + #endif + #ifdef _XBS5_LP64_OFF64 + printf(" 32-bit int, and 64-bit long, pointer, and off_t types are supported.\n"); + #else + printf(" 32-bit int, and 64-bit long, pointer, and off_t types are not supported.\n"); + #endif + #ifdef _XBS5_LPBIG_OFFBIG + printf(" 32 bits int and long, pointer, and off_t with at least 64 bits are supported.\n"); + #else + printf(" 32 bits int and long, pointer, and off_t with at least 64 bits are not supported.\n"); + #endif + + + #endif + //Do POSIX.1 tests + printf ("POSIX.1 Options Test Results:\n"); + #ifdef _POSIX_JOB_CONTROL + printf(" POSIX.1 Job control is supported.\n"); + #else + printf(" POSIX.1 Job control is not supported.\n"); + #endif + #ifdef _POSIX_CHOWN_RESTRICTED + printf(" POSIX.1 Chown restrictions are supported.\n"); + #else + printf(" POSIX.1 Chown restrictions are not supported.\n"); + #endif + #ifdef _POSIX_SAVED_IDS + printf(" POSIX.1 Process saved IDs are supported.\n"); + #else + printf(" POSIX.1 Process saved IDs are not supported.\n"); + #endif + #ifdef _POSIX_NO_TRUNC + printf(" POSIX.1 Long pathname errors are supported.\n"); + #else + printf(" POSIX.1 Long pathname errors are not supported.\n"); + #endif + #ifdef _POSIX_VDISABLE + printf(" POSIX.1 Some terminal charactistics disabling is supported.\n"); + #else + printf(" POSIX.1 Some terminal charactistics disabling is not supported.\n"); + #endif + #ifdef NGROUPS_MAX + printf(" POSIX.1 Supplementary group IDs is supported.\n"); + #else + printf(" POSIX.1 Supplementary group IDs is not supported.\n"); + #endif + + //System Run time testing + printf("\nSystem run time tests:\n"); + errno=0; + val=sysconf(_SC_JOB_CONTROL); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_JOB_CONTROL\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.1 JOB CONTROL not Supported.\n"); + } + else + { + printf("POSIX.1 JOB CONTROL Supported.\n"); + } + errno=0; + val=sysconf(_SC_SAVED_IDS); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_SAVED_IDS\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.1 SAVED IDS not Supported.\n"); + } + else + { + printf("POSIX.1 SAVED IDS Supported.\n"); + } + errno=0; + val=sysconf(_SC_VERSION); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_VERSION\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.1 VERSION not Supported.\n"); + } + else + { + printf("POSIX.1 VERSION Supported.\n"); + } + val=sysconf(_SC_ARG_MAX); + if (val == -1) + { + printf("Bad option _SC_ARG_MAX\n"); + } + else + { + printf("POSIX.1 ARG MAX Value=%ld.\n",val); + } + val=sysconf(_SC_CHILD_MAX); + if (val == -1) + { + printf("Bad option _SC_CHILD_MAX\n"); + } + else + { + printf("POSIX.1 CHILD MAX Value=%ld.\n",val); + } + val=sysconf(_SC_CLK_TCK); + if (val == -1) + { + printf("Bad option _SC_CLK_TCK\n"); + } + else + { + printf("POSIX.1 CLK TCK Value=%ld.\n",val); + } + val=sysconf(_SC_NGROUPS_MAX); + if (val == -1) + { + printf("Bad option _SC_NGROUPS_MAX\n"); + } + else + { + printf("POSIX.1 NGROUPS MAX Value=%ld.\n",val); + } + val=sysconf(_SC_OPEN_MAX); + if (val == -1) + { + printf("Bad option _SC_OPEN_MAX\n"); + } + else + { + printf("POSIX.1 OPEN MAX Value=%ld.\n",val); + } + val=sysconf(_SC_STREAM_MAX); + if (val == -1) + { + printf("Bad option _SC_STREAM_MAX\n"); + } + else + { + printf("POSIX.1 STREAM MAX Value=%ld.\n",val); + } + val=sysconf(_SC_TZNAME_MAX); + if (val == -1) + { + printf("Bad option _SC_TZNAME_MAX\n"); + } + else + { + printf("POSIX.1 TZNAME MAX Value=%ld.\n",val); + } + errno=0; + val=sysconf(_SC_ASYNCHRONOUS_IO); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_ASYNCHRONOUS_IO\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 ASYNCHRONOUS IO not Supported.\n"); + } + else + { + printf("POSIX.4 ASYNCHRONOUS IO Supported.\n"); + } + errno=0; + val=sysconf(_SC_MAPPED_FILES); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_MAPPED_FILES\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 MAPPED FILES not Supported.\n"); + } + else + { + printf("POSIX.4 MAPPED FILES Supported.\n"); + } + errno=0; + val=sysconf(_SC_MEMLOCK_RANGE); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_MEMLOCK_RANGE\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 MEMLOCK RANGE not Supported.\n"); + } + else + { + printf("POSIX.4 MEMLOCK RANGE Supported.\n"); + } + errno=0; + val=sysconf(_SC_MEMORY_PROTECTION); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_MEMORY_PROTECTION\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 MEMORY PROTECTION not Supported.\n"); + } + else + { + printf("POSIX.4 MEMORY PROTECTION Supported.\n"); + } + errno=0; + val=sysconf(_SC_MESSAGE_PASSING); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_MESSAGE_PASSING\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 MESSAGE PASSING not Supported.\n"); + } + else + { + printf("POSIX.4 MESSAGE PASSING Supported.\n"); + } + errno=0; + val=sysconf(_SC_PRIORITIZED_IO); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_PRIORITIZED_IO\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 PRIORITIZED IO not Supported.\n"); + } + else + { + printf("POSIX.4 PRIORITIZED IO Supported.\n"); + } + errno=0; + val=sysconf(_SC_PRIORITY_SCHEDULING); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_PRIORITY_SCHEDULING\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 PRIORITY SCHEDULING not Supported.\n"); + } + else + { + printf("POSIX.4 PRIORITY SCHEDULING Supported.\n"); + } + errno=0; + val=sysconf(_SC_REALTIME_SIGNALS); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_REALTIME_SIGNALS\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 REALTIME SIGNALS not Supported.\n"); + } + else + { + printf("POSIX.4 REALTIME SIGNALS Supported.\n"); + } + errno=0; + val=sysconf(_SC_SEMAPHORES); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_SEMAPHORES\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 SEMAPHORES not Supported.\n"); + } + else + { + printf("POSIX.4 SEMAPHORES Supported.\n"); + } + errno=0; + val=sysconf(_SC_FSYNC); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_FSYNC\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 FSYNC not Supported.\n"); + } + else + { + printf("POSIX.4 FSYNC Supported.\n"); + } + errno=0; + val=sysconf(_SC_SHARED_MEMORY_OBJECTS); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_SHARED_MEMORY_OBJECTS\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 SHARED_MEMORY_OBJECTS not Supported.\n"); + } + else + { + printf("POSIX.4 SHARED_MEMORY_OBJECTS Supported.\n"); + } + errno=0; + val=sysconf(_SC_SYNCHRONIZED_IO); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_SYNCHRONIZED_IO\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 SYNCHRONIZED IO not Supported.\n"); + } + else + { + printf("POSIX.4 SYNCHRONIZED IO Supported.\n"); + } + errno=0; + val=sysconf(_SC_TIMERS); + if ((val == -1) && (errno)) + { + printf("Bad option _SC_TIMERS\n"); + } + else if ((val == -1) && (!errno)) + { + printf("POSIX.4 TIMERS not Supported.\n"); + } + else + { + printf("POSIX.4 TIMERS Supported.\n"); + } + val=sysconf(_SC_AIO_LISTIO_MAX); + if (val == -1) + { + printf("Bad option _SC_AIO_LISTIO_MAX\n"); + } + else + { + printf("POSIX.4 AIO LISTIO MAX Value=%ld.\n",val); + } + val=sysconf(_SC_AIO_MAX); + if (val == -1) + { + printf("Bad option _SC_AIO_MAX\n"); + } + else + { + printf("POSIX.4 AIO MAX Value=%ld.\n",val); + } + val=sysconf(_SC_AIO_PRIO_DELTA_MAX); + if (val == -1) + { + printf("Bad option _SC_AIO_PRIO_DELTA_MAX\n"); + } + else + { + printf("POSIX.4 AIO PRIO DELTA MAX Value=%ld.\n",val); + } + val=sysconf(_SC_DELAYTIMER_MAX); + if (val == -1) + { + printf("Bad option _SC_DELAYTIMER_MAX\n"); + } + else + { + printf("POSIX.4 DELAYTIMER MAX Value=%ld.\n",val); + } + val=sysconf(_SC_MQ_OPEN_MAX); + if (val == -1) + { + printf("Bad option _SC_MQ_OPEN_MAX\n"); + } + else + { + printf("POSIX.4 MQ OPEN MAX Value=%ld.\n",val); + } + val=sysconf(_SC_MQ_PRIO_MAX); + if (val == -1) + { + printf("Bad option _SC_MQ_PRIO_MAX\n"); + } + else + { + printf("POSIX.4 MQ PRIO MAX Value=%ld.\n",val); + } + val=sysconf(_SC_PAGESIZE); + if (val == -1) + { + printf("Bad option _SC_PAGESIZE\n"); + } + else + { + printf("POSIX.4 PAGESIZE Value=%ld.\n",val); + } + val=sysconf(_SC_RTSIG_MAX); + if (val == -1) + { + printf("Bad option _SC_RTSIG_MAX\n"); + } + else + { + printf("POSIX.4 RTSIG MAX Value=%ld.\n",val); + } + val=sysconf(_SC_SEM_NSEMS_MAX); + if (val == -1) + { + printf("Bad option _SC_SEM_NSEMS_MAX\n"); + } + else + { + printf("POSIX.4 SEM NSEMS MAX Value=%ld.\n",val); + } + val=sysconf(_SC_SEM_VALUE_MAX); + if (val == -1) + { + printf("Bad option _SC_SEM_VALUE_MAX\n"); + } + else + { + printf("POSIX.4 SEM VALUE MAX Value=%ld.\n",val); + } + val=sysconf(_SC_SIGQUEUE_MAX); + if (val == -1) + { + printf("Bad option _SC_SIGQUEUE_MAX\n"); + } + else + { + printf("POSIX.4 SIGQUEUE MAX Value=%ld.\n",val); + } + val=sysconf(_SC_TIMER_MAX); + if (val == -1) + { + printf("Bad option _SC_TIMER_MAX\n"); + } + else + { + printf("POSIX.4 TIMER MAX Value=%ld.\n",val); + } + +#endif + + return 0; +} diff --git a/ros2_ws/src/ecl_lite/ecl_console/.cproject b/ros2_ws/src/ecl_lite/ecl_console/.cproject new file mode 100644 index 0000000..4d129e7 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/.cproject @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_console/.project b/ros2_ws/src/ecl_lite/ecl_console/.project new file mode 100644 index 0000000..44e57d0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/.project @@ -0,0 +1,27 @@ + + + ecl_console + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_console/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_console/.settings/language.settings.xml new file mode 100644 index 0000000..9316812 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_console/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_console/CHANGELOG.rst new file mode 100644 index 0000000..3aa4a95 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/CHANGELOG.rst @@ -0,0 +1,10 @@ +========= +Changelog +========= + +0.61.4 (2016-01-10) +------------------- +* namespaced to within the ecl +* imported from `termcolor`_ for our low-level cross-compiled embedded projects + +.. _`termcolor`: https://github.com/ikalnitsky/termcolor diff --git a/ros2_ws/src/ecl_lite/ecl_console/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_console/CMakeLists.txt new file mode 100644 index 0000000..6a774c1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/CMakeLists.txt @@ -0,0 +1,67 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_console) + +############################################################################## +# Find +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) + +############################################################################## +# Project configuration +############################################################################## + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Headers +############################################################################## + +install( + DIRECTORY include/ecl/ + DESTINATION include/ecl + FILES_MATCHING PATTERN "*.hpp" +) + +############################################################################## +# Header Library +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) +target_link_libraries(${PROJECT_NAME} INTERFACE ecl_config::ecl_config) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + INCLUDES DESTINATION include +) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies(ecl_config) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_console/doxygen/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_console/doxygen/mainpage.dox new file mode 100644 index 0000000..130552a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/doxygen/mainpage.dox @@ -0,0 +1,45 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + Provides a ansii colour library for the ansii console. + + +@section CompilingLinking Compiling & Linking + + Just include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Interface classes + using ecl::CmdLine; + using ecl::ArgException + // Argument classes + using ecl::SwitchArg; + using ecl::ValueArg; + using ecl::MultiArg; + using ecl::UnlabeledValueArg; + using ecl::UnlabeledMultiArg; // there are more - see tclap docs + @endcode + + + Since it is a template header library, no linking is required if you are + only using these classes. + +\section usage Usage + + @section extraHelp Further Help (termcolor) + + Most of termcolor's doxygen is generated automatically inside the ecl. For more detailed + documentation, read the manual at + readthedocs home page. + +\section ChangeLog + + - Oct 15 : initial import of the termcolor headers. + +*/ diff --git a/ros2_ws/src/ecl_lite/ecl_console/include/ecl/console.hpp b/ros2_ws/src/ecl_lite/ecl_console/include/ecl/console.hpp new file mode 100644 index 0000000..b75231b --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/include/ecl/console.hpp @@ -0,0 +1,519 @@ +//! +//! termcolor +//! ~~~~~~~~~ +//! +//! termcolor is a header-only c++ library for printing colored messages +//! to the terminal. Written just for fun with a help of the Force. +//! +//! :copyright: (c) 2013 by Igor Kalnitsky +//! :license: BSD, see LICENSE for details +//! + +#ifndef ecl_console_TERMCOLOR_HPP_ +#define ecl_console_TERMCOLOR_HPP_ + +// the following snippet of code detects the current OS and +// defines the appropriate macro that is used to wrap some +// platform specific things +#if defined(_WIN32) || defined(_WIN64) +# define OS_WINDOWS +#elif defined(__APPLE__) +# define OS_MACOS +#elif defined(linux) || defined(__linux) +# define OS_LINUX +#else +# error "unsupported platform" +#endif + + +// This headers provides the `isatty()`/`fileno()` functions, +// which are used for testing whether a standart stream refers +// to the terminal. As for Windows, we also need WinApi funcs +// for changing colors attributes of the terminal. +#if defined(OS_MACOS) || defined(OS_LINUX) +# include +#elif defined(OS_WINDOWS) +# include +# include +#endif + +#include +#include + +namespace ecl +{ + // Forward declaration of the `console` namespace. + // All comments are below. + namespace console + { + inline FILE* get_standard_stream(const std::ostream& stream); + inline bool is_atty(const std::ostream& stream); + + #if defined(OS_WINDOWS) + void win_change_attributes(std::ostream& stream, int foreground, int background=-1); + #endif + } + + + inline + std::ostream& reset(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[00m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, -1); + #endif + } + return stream; + } + + + inline + std::ostream& bold(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[1m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& dark(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[2m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& underline(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[4m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& blink(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[5m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& reverse(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[7m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& concealed(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[8m"; + #elif defined(OS_WINDOWS) + #endif + } + return stream; + } + + + inline + std::ostream& grey(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[30m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + 0 // grey (black) + ); + #endif + } + return stream; + } + + inline + std::ostream& red(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[31m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& green(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[32m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_GREEN + ); + #endif + } + return stream; + } + + inline + std::ostream& yellow(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[33m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_GREEN | FOREGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& blue(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[34m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_BLUE + ); + #endif + } + return stream; + } + + inline + std::ostream& magenta(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[35m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_BLUE | FOREGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& cyan(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[36m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_BLUE | FOREGROUND_GREEN + ); + #endif + } + return stream; + } + + inline + std::ostream& white(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[37m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, + FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED + ); + #endif + } + return stream; + } + + + + inline + std::ostream& on_grey(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[40m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + 0 // grey (black) + ); + #endif + } + return stream; + } + + inline + std::ostream& on_red(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[41m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& on_green(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[42m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_GREEN + ); + #endif + } + return stream; + } + + inline + std::ostream& on_yellow(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[43m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_GREEN | BACKGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& on_blue(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[44m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_BLUE + ); + #endif + } + return stream; + } + + inline + std::ostream& on_magenta(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[45m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_BLUE | BACKGROUND_RED + ); + #endif + } + return stream; + } + + inline + std::ostream& on_cyan(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[46m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_GREEN | BACKGROUND_BLUE + ); + #endif + } + return stream; + } + + inline + std::ostream& on_white(std::ostream& stream) + { + if (console::is_atty(stream)) + { + #if defined(OS_MACOS) || defined(OS_LINUX) + stream << "\033[47m"; + #elif defined(OS_WINDOWS) + console::win_change_attributes(stream, -1, + BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED + ); + #endif + } + + return stream; + } + + + + //! Since C++ hasn't a way to hide something in the header from + //! the outer access, I have to introduce this namespace which + //! is used for internal purpose and should't be access from + //! the user code. + namespace console + { + //! Since C++ hasn't a true way to extract stream handler + //! from the a given `std::ostream` object, I have to write + //! this kind of hack. + inline + FILE* get_standard_stream(const std::ostream& stream) + { + if (&stream == &std::cout) + return stdout; + else if (&stream == &std::cerr) + return stderr; + return nullptr; + } + + + //! Test whether a given `std::ostream` object refers to + //! a terminal. + inline + bool is_atty(const std::ostream& stream) + { + // DJS : don't worry about strict checking so we can use this with + // stringstreams. Upstream issue at https://github.com/ikalnitsky/termcolor/issues/5 + return true; + + FILE* std_stream = get_standard_stream(stream); + + + #if defined(OS_MACOS) || defined(OS_LINUX) + return ::isatty(fileno(std_stream)); + #elif defined(OS_WINDOWS) + return ::_isatty(_fileno(std_stream)); + #endif + } + + + #if defined(OS_WINDOWS) + //! Change Windows Terminal colors attribute. If some + //! parameter is `-1` then attribute won't changed. + void win_change_attributes(std::ostream& stream, int foreground, int background) + { + // yeah, i know.. it's ugly, it's windows. + static WORD defaultAttributes = 0; + + // get terminal handle + HANDLE hTerminal = INVALID_HANDLE_VALUE; + if (&stream == &std::cout) + hTerminal = GetStdHandle(STD_OUTPUT_HANDLE); + else if (&stream == &std::cerr) + hTerminal = GetStdHandle(STD_ERROR_HANDLE); + + // save default terminal attributes if it unsaved + if (!defaultAttributes) + { + CONSOLE_SCREEN_BUFFER_INFO info; + if (!GetConsoleScreenBufferInfo(hTerminal, &info)) + return; + defaultAttributes = info.wAttributes; + } + + // restore all default settings + if (foreground == -1 && background == -1) + { + SetConsoleTextAttribute(hTerminal, defaultAttributes); + return; + } + + // get current settings + CONSOLE_SCREEN_BUFFER_INFO info; + if (!GetConsoleScreenBufferInfo(hTerminal, &info)) + return; + + if (foreground != -1) + { + info.wAttributes &= ~(info.wAttributes & 0x0F); + info.wAttributes |= static_cast(foreground); + } + + if (background != -1) + { + info.wAttributes &= ~(info.wAttributes & 0xF0); + info.wAttributes |= static_cast(background); + } + + SetConsoleTextAttribute(hTerminal, info.wAttributes); + } + #endif // OS_WINDOWS + + } // namespace console + +} // namespace ecl + + +#undef OS_WINDOWS +#undef OS_MACOS +#undef OS_LINUX + +#endif // ecl_console_TERMCOLOR_HPP_ diff --git a/ros2_ws/src/ecl_lite/ecl_console/license/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_console/license/CMakeLists.txt new file mode 100644 index 0000000..c5480d3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/license/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# FILES +############################################################################### + +install(FILES LICENSE DESTINATION share/ecl/licenses/termcolor) + diff --git a/ros2_ws/src/ecl_lite/ecl_console/license/LICENSE b/ros2_ws/src/ecl_lite/ecl_console/license/LICENSE new file mode 100644 index 0000000..0905ac6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/license/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2013 by Igor Kalnitsky. +All rights reserved. + +Redistribution and use in source and binary forms of the software as well +as documentation, 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. + +* The names of the contributors may not be used to endorse or + promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE AND DOCUMENTATION 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 AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. diff --git a/ros2_ws/src/ecl_lite/ecl_console/package.xml b/ros2_ws/src/ecl_lite/ecl_console/package.xml new file mode 100644 index 0000000..328da08 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_console/package.xml @@ -0,0 +1,28 @@ + + + ecl_console + 1.2.0 + + Color codes for ansii consoles. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_console + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_license + ecl_build + ecl_config + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/.cproject b/ros2_ws/src/ecl_lite/ecl_converters_lite/.cproject new file mode 100644 index 0000000..275410a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/.cproject @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + clean + + true + + true + + true + + + + + + make + + + + all + + true + + true + + true + + + + + + make + + + + tests + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/.project b/ros2_ws/src/ecl_lite/ecl_converters_lite/.project new file mode 100644 index 0000000..1f456af --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/.project @@ -0,0 +1,79 @@ + + + ecl_converters_lite + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_converters_lite/.settings/language.settings.xml new file mode 100644 index 0000000..1e1e099 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_converters_lite/CHANGELOG.rst new file mode 100644 index 0000000..97b6a40 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/CHANGELOG.rst @@ -0,0 +1,4 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_converters_lite +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/CMakeLists.txt new file mode 100644 index 0000000..6a7cc88 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/CMakeLists.txt @@ -0,0 +1,64 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_converters_lite) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) +target_link_libraries(${PROJECT_NAME} INTERFACE ecl_config::ecl_config) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + INCLUDES DESTINATION include +) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies(ecl_config) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..00ab258 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(converters_lite) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite.hpp b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite.hpp new file mode 100644 index 0000000..94bfe56 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite.hpp @@ -0,0 +1,21 @@ +/** + * @file include/ecl/converters_lite.hpp + * + * @brief Collects headers for ecl_converters_lite. + * + * @date March 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_LITE_HPP_ +#define ECL_CONVERTERS_LITE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "converters_lite/byte_array.hpp" + +#endif /* ECL_CONVERTERS_LITE_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/CMakeLists.txt new file mode 100644 index 0000000..1ff45ba --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/converters_lite) diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/byte_array.hpp b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/byte_array.hpp new file mode 100644 index 0000000..32bd01b --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/include/ecl/converters_lite/byte_array.hpp @@ -0,0 +1,152 @@ +/** + * @file include/ecl/converters_lite/byte_array.hpp + * + * @brief Conversions between integers and byte arrays. + * + * @date March 2011. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_CONVERTERS_LITE_BYTE_ARRAY_HPP_ +#define ECL_CONVERTERS_LITE_BYTE_ARRAY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** From Byte Array +*****************************************************************************/ +/** + * @brief Converts an array of four char into a 32 bit integer. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of signed characters. + */ +void from_byte_array(int32 &value, const signed char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +/** + * @brief Converts an array of four char into a 32 bit integer. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of characters. + */ +void from_byte_array(int32 &value, const char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +/** + * @brief Converts a array of four unsigned char into a 32 bit integer. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of unsigned char. + */ +void from_byte_array(int32 &value, const unsigned char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +/** + * @brief Converts a array of four char into a 32 bit integer. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of signed char. + */ +void from_byte_array(uint32 &value, const signed char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +/** + * @brief Converts a array of four char into a 32 bit integer. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of char. + */ +void from_byte_array(uint32 &value, const char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +/** + * @brief Converts a array of four unsigned char into a 32 bit unsigned int. + * + * The bytes are ordered from least significant to most significant + * (little-endian). + * + * Warning: be careful to ensure that there is always + * at least 4 elements in the char string available for conversion. + * There is no way of catching this error except via segfault. + * + * @param value : the output integer + * @param byte_array : input array of unsigned char. + */ +void from_byte_array(uint32 &value, const unsigned char* byte_array) { + value = 0; + for (unsigned int i = 0; i < 4; ++i ) { + value |= static_cast(*(byte_array+i)) << 8*i; + } +} + +} // namespace ecl + +#endif /* ECL_CONVERTERS_LITE_BYTE_ARRAY_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_converters_lite/mainpage.dox new file mode 100644 index 0000000..76f2d5e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/mainpage.dox @@ -0,0 +1,60 @@ +/** +\mainpage +\htmlinclude manifest.html + + @section Introduction + + Lightweight converter functions suitable for control firmware + develompent. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The converter functions + using ecl::from_byte_array; + @endcode + + Since it is solely comprised of inline header functions, no linking is required if you are only using this class. + + @section ConvertersUsageSection Usage + + @subsection byteArray Byte Array Converters + + These convert between integral types and character arrays. This is quite + a common operation for control systems which are reading/writing to and + from i/o character devices (e.g. serial port). + + These functions do need some care as you're passing pointers which must + be pointing to memory with at least the required number of bytes + to do the conversion + + @code + ecl::int32 value; + char three_six_three[4] = { 0x6b, 0x01, 0x00, 0x00 }; + ecl::from_byte_array(value,three_six_three); + std::cout << value << std::endl; // prints 363. + // ...also unsigned int/char variants. + @endcode + + @section ConverterList Current List of Converters + + The following are listed with the 'to' type on the left and 'from' types on the right. + + - int32 : byte array (char*, uchar*) + - uint32 : byte array (char*, uchar*) + +\section unitTests Unit Tests + + - src/test/byte_array.cpp + +\section ChangeLog + + - Nar 11 : added from_byte_array functions. + + +*/ diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/package.xml b/ros2_ws/src/ecl_lite/ecl_converters_lite/package.xml new file mode 100644 index 0000000..ee36207 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/package.xml @@ -0,0 +1,31 @@ + + + ecl_converters_lite + 1.2.0 + + These are a very simple version of some of the functions in ecl_converters + suitable for firmware development. That is, there is no use of new, + templates or exceptions. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_converters_lite + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_config + ecl_license + ecl_config + ament_cmake_gtest + ament_lint_auto + ament_lint_common + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/CMakeLists.txt new file mode 100644 index 0000000..c05fa32 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/CMakeLists.txt @@ -0,0 +1,9 @@ +############################################################################## +# Subdirectories +############################################################################## + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + ament_lint_auto_find_test_dependencies() + add_subdirectory(test) +endif() diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/CMakeLists.txt new file mode 100644 index 0000000..e93a93e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################## +# Files +############################################################################## + +ament_add_gtest(test_byte_array byte_array.cpp) +target_link_libraries(test_byte_array ${PROJECT_NAME}) diff --git a/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/byte_array.cpp b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/byte_array.cpp new file mode 100644 index 0000000..5a98db8 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_converters_lite/src/test/byte_array.cpp @@ -0,0 +1,61 @@ +/** + * @file src/test/byte_array.cpp + * + * @brief Unit test for the byte array functions. + * + * @date March 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/converters_lite/byte_array.hpp" + +/***************************************************************************** +** Globals +*****************************************************************************/ + +bool debug_output = true; + +/***************************************************************************** +** Tests +*****************************************************************************/ + +TEST(ConverterTests, byteArrays) { + ecl::int32 value; + ecl::uint32 u_value; + char three_six_three[4] = { 0x6b, 0x01, 0x00, 0x00 }; + unsigned char u_three_six_three[4] = { 0x6b, 0x01, 0x00, 0x00 }; + // generates narrow conversion errors if lots of warnings are on + // char minus_two[4] = { 0xfe, 0xff, 0xff, 0xff }; + signed char minus_two[4] = { -2, -1, -1, -1 }; + signed char s_minus_two[4] = { -2, -1, -1, -1 }; + unsigned char u_minus_two[4] = { 0xfe, 0xff, 0xff, 0xff }; + ecl::from_byte_array(value, three_six_three); + if ( debug_output ) { std::cout << "value: " << value << std::endl; } + EXPECT_EQ(363,value); + ecl::from_byte_array(u_value, u_three_six_three); + if ( debug_output ) { std::cout << "value: " << u_value << std::endl; } + EXPECT_EQ(363u, u_value); + ecl::from_byte_array(value, minus_two); + if ( debug_output ) { std::cout << "value: " << value << std::endl; } + EXPECT_EQ(-2,value); + ecl::from_byte_array(value, s_minus_two); + if ( debug_output ) { std::cout << "value: " << value << std::endl; } + EXPECT_EQ(-2,value); + ecl::from_byte_array(value, u_minus_two); + if ( debug_output ) { std::cout << "value: " << value << std::endl; } + EXPECT_EQ(-2,value); +} + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int argc, char **argv) { + + testing::InitGoogleTest(&argc,argv); + return RUN_ALL_TESTS(); +} diff --git a/ros2_ws/src/ecl_lite/ecl_errors/.cproject b/ros2_ws/src/ecl_lite/ecl_errors/.cproject new file mode 100644 index 0000000..35c5ee5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/.cproject @@ -0,0 +1,658 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + clean + + true + + true + + true + + + + + + make + + + + all + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/.project b/ros2_ws/src/ecl_lite/ecl_errors/.project new file mode 100644 index 0000000..b1f178b --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/.project @@ -0,0 +1,78 @@ + + + ecl_errors + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_errors/.settings/language.settings.xml new file mode 100644 index 0000000..8090e02 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_errors/CHANGELOG.rst new file mode 100644 index 0000000..a497f36 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/CHANGELOG.rst @@ -0,0 +1,17 @@ +========= +Changelog +========= + +Forthcoming +----------- +* ... + +1.0.3 (2018-08-21) +------------------ +* pedantic error message fixes for ecl_compile_time_assert on clang/macosx +* explicit construction for the Error class so surprising things can't happen +* equality operator for the Error class + +0.61.1 (2015-07-26) +------------------- +* Add a missing virtual destructor diff --git a/ros2_ws/src/ecl_lite/ecl_errors/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/CMakeLists.txt new file mode 100644 index 0000000..6e49a75 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/CMakeLists.txt @@ -0,0 +1,46 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_errors) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies(ecl_config) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_errors/doxygen/changelog.dox b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/changelog.dox new file mode 100644 index 0000000..0a8c859 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/changelog.dox @@ -0,0 +1,20 @@ +/** + @page changelog ChangeLog + + @section Changes + + - Mar 13 : msvc port. + - Feb 11 : Moved runtime functions/macros to :: with ecl_ prefix. + - Feb 11 : Moved exception classes out to ecl_exceptions. + - May 10 : Cmake win32 framework. + - May 09 : @ref ecl_compile_time_assert adds a compile time logical check for templatised classes. + - Apr 09 : Includes several @ref Macros "macros" for throwing in debug mode and/or with conditional checks. + - Apr 09 : ecl_run_time_assert customises and extends the usual assert() style conditional checks when debugging [Apr 09]. + - Apr 09 : ecl_run_time_abort customises and extends the usual abort() style program exits [Apr 09]. + + @section Bugs + + - Nov 09 : Fixed an issue which wouldn't permit multiple uses of compile time asserts. + - May 09 : The standard assert macro kept getting in the way of our asserts, so it's been obliterated. + +**/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/doxygen/debugging.dox b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/debugging.dox new file mode 100644 index 0000000..8bf5b01 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/debugging.dox @@ -0,0 +1,91 @@ +/** + @page debugging Debugging the Ecl + + @section intro Bit of Background + + There are two types of errors that can arise and three main methods of dealing with these. These are listed below for + reference. + + @subsection errorTypes Error Types + + - Dynamic Errors - errors caused from unpredictable input (e.g. input from a user). + - Programming Errors - caused by developer bugs (e.g. out of range errors on containers). + + @subsection errorHandlingTechniques Error Handling Techniques + + - Assert and Abort Macros - these are unrecoverable, but simple to use. + - Exceptions - these are recoverable and force handling of error situations, but the stack unwinding is costly. + - Return Codes/Flags - these are recoverable, but require diligence on the part of the user to utilise properly. + + @subsection comparison Comparisons + + Assert and Abort Macros are typically undesirable for a library. Often a library user will want to recover from errors + and handle them using whatever mechanisms their application is using. A good example of this (that I'm currently using with + the ecl) are RoS nodes. Errors need to be caught and the program gracefully exited from the RoS node network. + + Return Codes/Flags are used in alot of places, for example, posix uses them to regular effect. They do have the drawback + of leaving objects in a zombie state when things go wrong and its up to the user to make sure they diligently check after + each operation that everything is still ok. This is alot of programming work. I find it also actually requires alot of + programming to ensure the classes behave correctly and avoid problems when in zombie states - this uses alot of + if conditionals throughout the program, so sometimes is not quite as costless as you imagine. + + Exception Handling when used with care and in the right places provides a much easier and cleaner solution. However, + they do slow the program down, particularly for oft used checks (range errors on containers). In embedded systems and games this + is often avoided for the cost it imparts. + + @section theECL What the ECL Does for Debugging + + In every case, more information on the error handling method used for a given class will be given in that class's documentation. + However, in general, ecl adheres to the following guidelines: + + @subsection fastCode Fast Code Blocks + + For functions that are typically used within a fast code block, particularly inside a control loop, debug mode provides + many warning/error exception handlers that are turned off in release mode. See below for details on how to switch the ecl + between debug and release modes. + + @subsection configurationCode Configuration/Initialisation + + Code that is often associated with configuration and initialisation will use exceptions in both debug and release modes. + See the ecl_exceptions package for more details. + + This includes many of the RAII style constructors that that open devices, configure mutexes etc. For control programs, this + stage of the program's lifecycle places a greater emphasis on stability, getting things going right rather than speed and as + a consequence, the cost of the stack unwinding is largely irrelevant. For functions that are typically nested inside a + control loop, exception handling is enabled only in debug mode. + + @subsection memoryDebuggingStack Memory Debugging Under/Overruns + + The biggest problems with alot of c-style code occur with arrays which are typically plagued by + buffer overflow (underrun or overrun) problems. Currently, the ecl has a mechansim to check + for this if ecl's array types (ecl_containers) are used in conjunction with a predefined macro + and manual code checks for overflows. See the documentation for ecl_containers for more information. + + @section detailedNotes Detailed Notes + + @subsection compilingLinking Debug Mode + + - Do not define the NDEBUG or the ECL_NDEBUG macro. + - Link to the _debug versions of the libraries. + + For example, a debug build might look like: + + @code + g++ -lecl_devices -o hello hello.cpp + @endcode + + Debug mode includes alot of warnings and error handlers for such things as invalid constructor configurations, + out of range container warnings, etc. + + @subsection compilingLinkingRelease Release Mode + + - Define either the NDEBUG or the ECL_NDEBUG macro. + - Link to the regularly named library. + + For example, + + @code + g++ -DNDEBUG -lecl_devices -o hello hello.cpp + @endcode + +**/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/doxygen/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/mainpage.dox new file mode 100644 index 0000000..79a2a5d --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/doxygen/mainpage.dox @@ -0,0 +1,131 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + The usual C++ means is to use exceptions, however in embedded systems, + exceptions are often unavailable or are too resource-heavy. + This library provides a simpler alternative, combining error flags, + macros and an error handler class to provide convenient disposal of + errors across multiple platforms. + + It also provides simple runtime and compile time asserts + and aborts. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit: + + @code + #include + + // The error interfaces + using ecl_compile_time_assert; + using ecl_run_time_assert; + using ecl_run_time_abort; + + // Error type enumerations + using ecl::NoError; + using ecl::ConfigurationError; + using ecl::UnknownError; + //... + + // Error Handler + using ecl::Error; + @endcode + + You will also need to link to -lecl_errors. + +@section Usage + + @subsection locSection LOC + + The macro, @ref LOC, is a means of picking up the current file and line number of the + point at which it is processed. Use with the various error functions and + functors defined in ecl::errors; + + @subsection errorHandlers Error Handling + + A set of flags is provided through the enumeration + @ref ecl::ErrorFlag "ErrorFlag". These, when coupled with the + @ref ecl::Error "errorhandler" class and @ref LOC macro provide + a convenient means of quickly identifying errors produced by the + ecl libraries regardless of the platform that is used. + + @code + ecl::Error void f(const int &i) const { + if ( i == 3 ) { + return ecl::Error(ecl::NoError); + } else { + return ecl::Error(ecl::OutOfRangeError); + } + int main() { + ecl::Error error = f(5); + if ( error.flag() != NoError() ) { + error.print(loc); + } + // output is ~ 'my_main.cpp : 31 - Out of range error.' + return 0; + } + @endcode + + The @ref ecl::Error "Error" class can be extended to customise the + error messages - refer to the ecl_time_lite package and the ecl::TimeError + class for an example. + + @subsection errorFunctions Assert and Abort Functions + + These functions, because they are coupled with fallback + macros are the only functions in the ecl not namespaced + inside the ecl namespace. Rather they are prefixed with ecl_. + + The ecl_run_time_assert macro/function is a tool for conditional testing. It is + governed by the presence of the NDEBUG macro. If NDEBUG is + absent (either in your code or c-flagged by the compiler (-DNDEBUG) + then run_time_assert will equate to a macro that defers to a null function pointer. + This is the fastest means of bypassing debugged code. + + If NODEBUG is present, then ecl_run_time_assert will act as a conditional test via an + function. If the test fails, it will output some data (that you + have passed to the function) before finally aborting. + + @code + int i = 3; + int j = 2; + ecl_run_time_assert(i < j, LOC, "Illegal context, need i < j"); + @endcode + + The abort macro/function works similarly except that it does no conditional test and + it is not negated by the presence of NDEBUG. + + @subsection compileSection Compile Time Equivalents + + There is also a macro which works like the compile time equivalent of ecl_run_time_assert(). + This macro is useful for checking template parameters mostly. When passed a logical + condition which fails, an eye-catching COMPILE_TIME_FAILURE is reported in the compile log. + + @code + ecl_compile_time_assert( 1 > 3 ) + @endcode + + Corresponding failure is reported in a format similar to the example output shown below: + + @code + test.cpp:47: error: invalid application of ‘sizeof’ to incomplete type ‘COMPILE_TIME_FAILURE’ + @endcode + +@section otherGuides Other Notes + + A short ramble on how the ecl handles debugging can be found in this @ref debugging "guide". +@section unitTests Unit Tests + + Not gtests, but a useful enough coverage style test. + + - src/examples/errors.cpp + +@section ChangeLog + + - @ref changelog "ChangeLog" + +*/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/include/CMakeLists.txt new file mode 100644 index 0000000..7a2e2b5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..c6c5485 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/CMakeLists.txt @@ -0,0 +1,14 @@ +############################################################################### +# SUBDIRECTORIES +############################################################################### + +add_subdirectory(errors) + +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors.hpp new file mode 100644 index 0000000..fe6706a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors.hpp @@ -0,0 +1,34 @@ +/** + * @file /include/ecl/errors.hpp + * + * @brief Macros for error-checking and program termination. + * + * @date April, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_HPP_ +#define ECL_ERRORS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "errors/macros.hpp" +#include "errors/handlers.hpp" +#include "errors/compile_time_assert.hpp" +#include "errors/run_time_functions.hpp" + +/***************************************************************************** +** Doxygen +*****************************************************************************/ + +/** + * @defgroup Macros Macros + * + * Macros that characterise the platform's time implementation. +**/ + +#endif /* ECL_ERRORS_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/CMakeLists.txt new file mode 100644 index 0000000..0d55112 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################### +# FILES +############################################################################### + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/errors) diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/compile_time_assert.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/compile_time_assert.hpp new file mode 100644 index 0000000..9661a26 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/compile_time_assert.hpp @@ -0,0 +1,85 @@ +/** + * @file /include/ecl/errors/compile_time_assert.hpp + * + * @brief Compile time checks. + * + * Macros and classes that allow compile time checking of conditional checks. + * + * @date May 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_COMPILE_TIME_ASSERT_HPP_ +#define ECL_ERRORS_COMPILE_TIME_ASSERT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @cond DOXYGEN_IGNORE_THIS + */ + +template struct COMPILE_TIME_FAILURE; + +template <> struct COMPILE_TIME_FAILURE {}; + +template struct static_assert_test {}; + +} // namespace ecl +/** + * @endcond + */ + +/** + * @brief Compile time equivalent of the usual assert (ecl/c) functions. + * + * @ingroup Macros + * + * This macro tests logical conditions at compile time, useful for template classes. + * When it fails, the compile aborts and flashes an eye catching message including + * COMPILE_TIME_FAILURE in the output along with the line of code where the test fails. + * + * The idea for this comes from boost where a similar implementation is used in + * the unit testing facility. + */ +#define ecl_compile_time_assert( logical_expression ) \ + typedef ecl::static_assert_test(logical_expression) >)> JOIN(compile_time_check,__LINE__) [[gnu::unused]] + +/** + * @brief Verbose compile time assert. + * + * @ingroup Macros + * + * This is similar to compile_time_assert, but simply adds a string message to + * its list of arguments. Note - this string must not contain spaces - the + * best way to use it is to use caps and underscores, then the message output + * is in sync with the COMPILE_TIME_FAILURE that will be emitted when the + * assertion fails. + * + * Recognition for this code must go to the author of the stones of nvwa (zlib license). + * + * http://sourceforge.net/projects/nvwa + */ +// If the (void)ERROR_##message is absent, we get unused variable warnings. +#define ecl_verbose_compile_time_assert( logical_expression, message ) \ + { \ + ecl::COMPILE_TIME_FAILURE<( (logical_expression) != 0)> ERROR_##message; \ + (void)ERROR_##message; \ + } + +#endif /* ECL_ERRORS_COMPILE_TIME_ASSERT_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/flags.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/flags.hpp new file mode 100644 index 0000000..2abbe5b --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/flags.hpp @@ -0,0 +1,70 @@ +/** + * @file /ecl_errors/include/ecl/errors/flags.hpp + * + * @brief Flags for error types. + * + * @date April, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_FLAGS_HPP_ +#define ECL_ERRORS_FLAGS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + + +/***************************************************************************** +** Error Flags +*****************************************************************************/ +/** + * @brief Enumerated flags for error message handling. + * + * These are simple flags to identify the type of error when it occurs. Use + * with the Error class (and its child classes, e.g. TimeError) to identify + * errors and get verbose string output when debugging. + */ +enum ErrorFlag { + NoError = 0, /**< No error (often a meaningful error state in itself). **/ + UnknownError = -1, /**< Unknown error type. **/ + OutOfRangeError = -2, /**< Tried to access beyond the range of the object (usually container). **/ + ConstructorError = -3, /**< An error occurred somewhere inside a class constructor. **/ + DestructorError = -4, /**< The destructor failed to self-destruct. **/ + ConversionError = -5, /**< A conversion (usually between types) failed. **/ + OpenError = -6, /**< Failed to open an input/output device. **/ + CloseError = -7, /**< Failed to close an input/output device. **/ + InvalidArgError = -8, /**< The user entered an invalid argument to this method, c.f. InvalidObjectError. **/ + ConfigurationError = -9, /**< There was a configuration error (usually in a configure() or initialise() method). **/ + ConnectionError = -10, /**< There was a connection error, usually with input-output devices. **/ + ReadError = -11, /**< There was a read error, usually with input-output devices. **/ + WriteError = -12, /**< There was a write error, usually with input-output devices. **/ + NotInitialisedError = -13, /**< The target object has not yet been initialised, accessing before doing so is not permitted. **/ + PermissionsError = -14, /**< The caller does not have the required permissions. **/ + MemoryError = -15, /**< There was a problem allocating the requested memory. **/ + UsageError = -16, /**< The object was used incorrectly and caused an error. **/ + RaiiError = -17, /**< The object is pure RAII style and must be initialised properly. **/ + ArgNotSupportedError = -18, /**< The combination of input arguments is not supported on this platform.**/ + NotSupportedError = -19, /**< This operation is not supported on this platform. **/ + BusyError = -20, /**< Resources are busy, operation is not permitted. **/ + OutOfResourcesError = -21, /**< Out of resources, cannot proceed. **/ + InterruptedError = -22, /**< This operation was interrupted. **/ + BlockingError = -23, /**< A device marked as blocking, but used as non-blocking, or vice versa. **/ + SystemFailureError = -24, /**< A subcomponent of the system platform has failed (e.g. io subsystem). **/ + InvalidObjectError = -25, /**< Attempted to work on an invalid object (e.g. dir instead of a file), c.f. InvalidArgError **/ + IsLockedError = -26, /**< Invalidates attempts to work further because an object is locked. **/ + TimeOutError = -27, /**< A timeout occured. **/ + NotFoundError = -28, /**< An object was not found. **/ + ConnectionRefusedError = -29, /**< A connection was refused by the other end (e.g. socket client server connections). **/ + PosixError = -101, /**< Deprecating. **/ + InvalidInputError = -103 /**< Deprecated. **/ +}; + + +} // namespace ecl + +#endif /* ECL_ERRORS_FLAGS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/handlers.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/handlers.hpp new file mode 100644 index 0000000..8940e64 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/handlers.hpp @@ -0,0 +1,181 @@ +/** + * @file /ecl_errors/include/ecl/errors/handlers.hpp + * + * @brief Error handling without exceptions. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_HANDLERS_HPP_ +#define ECL_ERRORS_HANDLERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include "macros.hpp" +#include "flags.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief The primary error handler for ecl libraries. + * + * This class is mostly used as the return type for ecl functions + * to indicate errors. + * + * @code + * Error f(const int &i) { + * if ( i == 3 ) { + * return Error(NoError); + * else { + * return Error(OutOfRangeError); + * } + * } + * + * // code + * + * Error error = f(5); + * if ( error.flag() != NoError ) { + * std::cout << error.what() << std::endl; // OR + * error.print(LOC); // for a verbose message with code location added. + * } + * @endcode + * + * Alternatively the class can be inherited and the verbose messages overloaded. + * Refer to the TimeError class in ecl_time_lite for an example. + */ +class ecl_errors_PUBLIC Error { +public: + /** + * @brief Configure the return type with an error flag. + * + * @param flag : the type of error that is to be returned. + */ + explicit Error(const ErrorFlag& flag = UnknownError) : error_flag(flag) {} + virtual ~Error() {} + + /** + * @brief The flag identifying the error identified with this error handler. + * @return ErrorFlag : the error flag + */ + virtual ErrorFlag flag() const { return error_flag; } + virtual void operator=(const ErrorFlag &error) { error_flag = error; } + /** + * @brief Comparison operator + * @return bool : the result of the comparison + */ + virtual bool operator==(const Error &other) { return (error_flag == other.error_flag); } + +// virtual void debug(const char* loc) { +// #if !defined(NDEBUG) && !defined(ECL_NDEBUG) +// printf("%s - %s\n",loc,what()); +// #endif +// } + + /** + * @brief Print a location dependent message to standard out. + * + * Usage: + * + * @code + * Error error = f(5); + * if ( error.flag() != NoError ) { + * error.print(LOC); + * } + * @endcode + * @param loc : use with the LOC macro. + */ + virtual void print(const char* loc) { + printf("%s - %s\n",loc,what()); + } + + /** + * @brief A simple string verbosely representing the error that is handled. + * + * @return const char* : verbose representation of the error. + */ + virtual const char* what() const { + switch (error_flag) { + case (NoError) : { return noErrorString(); } + case (OutOfRangeError) : { return outOfRangeErrorString(); } + case (ConstructorError) : { return constructorErrorString(); } + case (DestructorError) : { return destructorErrorString(); } + case (ConversionError) : { return conversionErrorString(); } + case (OpenError) : { return openErrorString(); } + case (CloseError) : { return closeErrorString(); } + case (InvalidArgError) : { return invalidArgErrorString(); } + case (ConfigurationError) : { return configurationErrorString(); } + case (ConnectionError) : { return connectErrorString(); } + case (ReadError) : { return readErrorString(); } + case (WriteError) : { return writeErrorString(); } + case (NotInitialisedError) : { return notInitialisedErrorString(); } + case (PermissionsError) : { return permissionsErrorString(); } + case (MemoryError) : { return memoryErrorString(); } + case (UsageError) : { return usageErrorString(); } + case (RaiiError) : { return raiiErrorString(); } + case (ArgNotSupportedError) : { return argNotSupportedErrorString(); } + case (NotSupportedError) : { return notSupportedErrorString(); } + case (BusyError) : { return busyErrorString(); } + case (OutOfResourcesError) : { return outOfResourcesErrorString(); } + case (InterruptedError) : { return interruptedErrorString(); } + case (BlockingError) : { return blockingErrorString(); } + case (SystemFailureError) : { return systemFailureErrorString(); } + case (InvalidObjectError) : { return invalidObjectErrorString(); } + case (IsLockedError) : { return isLockedErrorString(); } + case (TimeOutError) : { return isTimeOutErrorString(); } + case (NotFoundError) : { return notFoundErrorString(); } + case (ConnectionRefusedError) : { return connectionRefusedString(); } + + default : { return unknownErrorString(); } // also covers the 'UnknownError flag. + } + } +protected: + virtual const char* noErrorString() const { return "No error."; } + virtual const char* outOfRangeErrorString() const { return "Out of range error - tried to access beyond the range of the object (usually container)."; } + virtual const char* constructorErrorString() const { return "The constructor did not produce a valid object."; } + virtual const char* destructorErrorString() const { return "The destructor failed to self destruct."; } + virtual const char* conversionErrorString() const { return "Conversion from one type to another failed."; } + virtual const char* openErrorString() const { return "Could not open the requested object."; } + virtual const char* closeErrorString() const { return "Could not close the requested object."; } + virtual const char* invalidArgErrorString() const { return "One of the supplied input arguments was invalid."; } + virtual const char* configurationErrorString() const { return "There was a configuration error."; } + virtual const char* connectErrorString() const { return "Could not connect."; } + virtual const char* readErrorString() const { return "Could not read from the object."; } + virtual const char* writeErrorString() const { return "Could not write to the object."; } + virtual const char* notInitialisedErrorString() const { return "The object has not been properly initialised yet."; } + virtual const char* permissionsErrorString() const { return "The caller does not have the required permissions."; } + virtual const char* memoryErrorString() const { return "There was a problem allocating the requested memory."; } + virtual const char* usageErrorString() const { return "The object was used incorrectly."; } + virtual const char* raiiErrorString() const { return "The object is pure RAII style and must be initialised correctly, you may not use the default constructor."; } + virtual const char* argNotSupportedErrorString() const { return "The combination of input arguments is not supported on this platform."; } + virtual const char* notSupportedErrorString() const { return "This operation is not supported on this platform."; } + virtual const char* busyErrorString() const { return "Resources are busy, operation is not permitted"; } + virtual const char* outOfResourcesErrorString() const { return "Out of resources, cannot proceed."; } + virtual const char* interruptedErrorString() const { return "This operation was interrupted."; } + virtual const char* blockingErrorString() const { return "A device marked as blocking, but used as non-blocking, or vice versa."; } + virtual const char* systemFailureErrorString() const { return "A subsystem has failed mid operation."; } + virtual const char* invalidObjectErrorString() const { return "Attempted to work on an invalid object."; } + virtual const char* isLockedErrorString() const { return "Invalidates attempts to work further because an object is locked."; } + virtual const char* isTimeOutErrorString() const { return "A timeout occured."; } + virtual const char* notFoundErrorString() const { return "The resource could not be found."; } + virtual const char* connectionRefusedString() const { return "The connection was refused by the listener at the other end of the connection."; } + virtual const char* unknownErrorString() const { return "Unknown error."; } + + ErrorFlag error_flag; +}; + + +} // namespace ecl + +#endif /* ECL_ERRORS_HANDLERS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/macros.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/macros.hpp new file mode 100644 index 0000000..c48e5a6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/macros.hpp @@ -0,0 +1,70 @@ +/** + * @file /include/ecl/errors/macros.hpp + * + * @brief Macros for error-checking and program termination. + * + * Macros for error-checking and program termination. + * + * @date April 2013. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_MACROS_HPP_ +#define ECL_ERRORS_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** PreProcessing +*****************************************************************************/ +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_errors_EXPORTS // we are building a shared lib/dll + #define ecl_errors_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_errors_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_errors_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_errors_PUBLIC + #define ecl_errors_LOCAL +#endif + +/* + * Convert a variable name to a string. + */ +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) + +/* + * Joints two arguments together. + * The following piece of macro magic joins the two + * arguments together, even when one of the arguments is + * itself a macro (see 16.3.1 in C++ standard). The key + * is that macro expansion of macro arguments does not + * occur in BOOST_DO_JOIN2 but does in BOOST_DO_JOIN. + */ +#define JOIN( X, Y ) DO_JOIN( X, Y ) +#define DO_JOIN( X, Y ) DO_JOIN2(X,Y) +#define DO_JOIN2( X, Y ) X##Y + +/** + * @ingroup Macros + * + * @brief Stringify the line of code you are at. + * + * This uses a couple of simpler string macros to indicate in which file and at what + * line this piece of code is at. + */ +#define LOC __FILE__ ":" TOSTRING(__LINE__) " " + + +#endif /* ECL_ERRORS_MACROS_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/run_time_functions.hpp b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/run_time_functions.hpp new file mode 100644 index 0000000..e362003 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/include/ecl/errors/run_time_functions.hpp @@ -0,0 +1,97 @@ +/** + * @file /include/ecl/errors/run_time_functions.hpp + * + * @brief Functions for error-checking and program termination. + * + * Functions for error-checking and program termination. + * + * @date April, 2009 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_ERRORS_ERROR_FUNCTIONS_HPP_ +#define ECL_ERRORS_ERROR_FUNCTIONS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "handlers.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +/***************************************************************************** +** Functions [run_time_assert] +*****************************************************************************/ + +#if defined(NDEBUG) || defined(ECL_NDEBUG) + #define ecl_run_time_assert(req,loc,msg) ((void)0) +#else + /** + * @brief Condition test, aborts with a programmable error string if it fails. + * + * Tests an assertion and if it fails, it writes a message (file, line# and + * warning) to stderror before aborting the program (and if on *nix, core + * dumping). This allows a customised user string for the error message. + * + * This function is only available if NDEBUG is not set (i.e. debug mode). + * + * @param requirement : logic expression to test for truthfulness. + * @param location : code location, use the LOC macro. + * @param msg : customised error string. + * + * @sa LOC + **/ + ecl_errors_PUBLIC void ecl_run_time_assert ( bool requirement, const char* location, const char* msg); + /** + * @brief Condition test, aborts with a predefined error string if it fails. + * + * Tests an assertion and if it fails, it writes a message (file, line# and + * warning) to stderror before aborting the program (and if on *nix, core + * dumping). This uses a pre-defined error flag to generate the error message. + * + * This function is only available if NDEBUG is not set (i.e. debug mode). + * + * @param requirement : logic expression to test for truthfulness. + * @param location : code location, use the LOC macro. + * @param type : predefined error message tag. + * + * @sa LOC. + **/ + ecl_errors_PUBLIC void ecl_run_time_assert ( bool requirement, const char* location, ecl::ErrorFlag type); +#endif + +/***************************************************************************** +** Functions [abort] +*****************************************************************************/ + +/** + * @brief Puts a customised error string to stderr before aborting the program. + * + * Writes an error message to stderror before promptly aborting. Note that this one + * is not affected by the presence/absence of the macro NDEBUG. + * @param location : code location, use the LOC macro. + * @param msg : customised error string. + * + * @sa LOC + **/ +ecl_errors_PUBLIC void ecl_run_time_abort ( const char* location, const char* msg = "Abort procedure called."); +/** + * @brief Puts a predefined error string to stderr before aborting the program. + * + * Writes an error message to stderror before promptly aborting with a pre-defined error message. + * Note that this one is not affected by the presence/absence of the macro NDEBUG. + * @param location : code location, use the LOC macro. + * @param type : predefined error message type tag. + * + * @sa LOC + **/ +ecl_errors_PUBLIC void ecl_run_time_abort ( const char* location, ecl::ErrorFlag type ); + +#endif /* ECL_ERRORS_ERROR_FUNCTIONS_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_errors/package.xml b/ros2_ws/src/ecl_lite/ecl_errors/package.xml new file mode 100644 index 0000000..aa161a9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/package.xml @@ -0,0 +1,30 @@ + + + ecl_errors + 1.2.0 + + This library provides lean and mean error mechanisms. + It includes c style error functions as well as a few + useful macros. For higher level mechanisms, + refer to ecl_exceptions. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_errors + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_license + ecl_config + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/src/CMakeLists.txt new file mode 100644 index 0000000..f68c7dd --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/src/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################### +# Subdirectories +############################################################################### + +add_subdirectory(lib) +add_subdirectory(examples) diff --git a/ros2_ws/src/ecl_lite/ecl_errors/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/src/examples/CMakeLists.txt new file mode 100644 index 0000000..33cbf0c --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/src/examples/CMakeLists.txt @@ -0,0 +1,22 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_errors_add_example name) + set(target_name ecl_errors_example_${name}) + add_executable(${target_name} ${name}.cpp) + target_link_libraries(${target_name} + ${PROJECT_NAME} + ) + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME demo_${name}) + if(CMAKE_COMPILER_IS_GNUCXX) + set_target_properties(${target_name} PROPERTIES COMPILE_FLAGS "-Wno-unused-local-typedefs") + endif() + install(TARGETS ${target_name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################### +# Examples +############################################################################### + +ecl_errors_add_example(errors) diff --git a/ros2_ws/src/ecl_lite/ecl_errors/src/examples/errors.cpp b/ros2_ws/src/ecl_lite/ecl_errors/src/examples/errors.cpp new file mode 100644 index 0000000..d79fd38 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/src/examples/errors.cpp @@ -0,0 +1,74 @@ +/** + * @file /src/examples/errors.cpp + * + * @brief Unit Test for ecl error functions and macros. + * + * @date April, 2009 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/errors/compile_time_assert.hpp" +#include "../../include/ecl/errors/handlers.hpp" +#include "../../include/ecl/errors/run_time_functions.hpp" +#include "../../include/ecl/errors/macros.hpp" + + +/***************************************************************************** +** Globals +*****************************************************************************/ +/** + * @cond IGNORE_THIS + */ +template +class Test { +public: + Test() { + ecl_compile_time_assert( M >= 0 ); + ecl_compile_time_assert( N >= 0 ); + } +}; +/** + * @endcond + */ +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Error functions" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Constructing an error of type 'Unknown Error'" << std::endl; + std::cout << std::endl; + ecl::Error error(ecl::UnknownError); + std::cout << "Error::what() " << std::endl; + std::cout << error.what() << std::endl; + std::cout << "Error::print(LOC) " << std::endl; + error.print(LOC); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Asserts and Aborts" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::Error configuration_error(ecl::ConfigurationError); + Test<3,1> test; +// ecl_compile_time_assert(1 >= 3); +// ecl_verbose_compile_time_assert( 1 >= 0, BAD_INEQUALITY ); +// ecl_run_time_abort ( LOC, ConfigurationError ); +// ecl_run_time_abort ( LOC, "Custom error report." ); + ecl_run_time_assert ( 2 < 1, LOC, configuration_error.flag() ); +// ecl_run_time_assert ( 2 < 1, LOC, ConfigurationError ); +// ecl_run_time_assert ( 2 < 1, LOC, "Inequality broken." ); + + return 0; +} + diff --git a/ros2_ws/src/ecl_lite/ecl_errors/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_errors/src/lib/CMakeLists.txt new file mode 100644 index 0000000..c6ddba1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/src/lib/CMakeLists.txt @@ -0,0 +1,34 @@ +############################################################################### +# Sources +############################################################################### + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) + +target_link_libraries(${PROJECT_NAME} + PUBLIC ecl_config::ecl_config +) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_lite/ecl_errors/src/lib/run_time_functions.cpp b/ros2_ws/src/ecl_lite/ecl_errors/src/lib/run_time_functions.cpp new file mode 100644 index 0000000..2718a85 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_errors/src/lib/run_time_functions.cpp @@ -0,0 +1,75 @@ +/** + * @file /src/lib/run_time_functions.cpp + * + * @brief Implementation for the error functions. + * + * @date April, 2009 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/errors/run_time_functions.hpp" +#include "../../include/ecl/errors/handlers.hpp" + +/***************************************************************************** +** Function Implementation [assert] +*****************************************************************************/ + +#if defined(NDEBUG) || defined(ECL_NDEBUG) +#else + void ecl_run_time_assert ( bool requirement, const char* location, const char* msg) + { + if ( !requirement ) + { + fputs ("Location : ", stderr); + fputs ( location ,stderr); + fputs ("\n", stderr); + fputs ("Message : ", stderr); + fputs ( msg, stderr); + fputs ( "\n", stderr); + ::abort(); + } + } + void ecl_run_time_assert ( bool requirement, const char* location, ecl::ErrorFlag type) + { + if ( !requirement ) + { + fputs ("Location : ", stderr); + fputs ( location ,stderr); + fputs ("\n", stderr); + fputs ("Message : ", stderr); + fputs ( ecl::Error(type).what(), stderr); + fputs ( "\n", stderr); + ::abort(); + } + } +#endif + + +/***************************************************************************** +** Function Implementation [abort] +*****************************************************************************/ + +void ecl_run_time_abort ( const char* location, const char* msg) +{ + fputs ( "Location : ", stderr); + fputs ( location, stderr); + fputs ("\nMessage : ", stderr); + fputs ( msg, stderr); + fputs ( "\n", stderr); + ::abort(); +} + +void ecl_run_time_abort ( const char* location, ecl::ErrorFlag type ) +{ + fputs ( "Location : ", stderr); + fputs ( location,stderr); + fputs ("\nMessage : ", stderr); + fputs ( ecl::Error(type).what(), stderr); + fputs ( "\n", stderr); + ::abort(); +} + diff --git a/ros2_ws/src/ecl_lite/ecl_io/.cproject b/ros2_ws/src/ecl_lite/ecl_io/.cproject new file mode 100644 index 0000000..ee4f898 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/.cproject @@ -0,0 +1,686 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + clean + + true + + true + + true + + + + + + make + + all + + true + + true + + true + + + + + + make + + examples + + true + + true + + true + + + + + + make + + + + win + + true + + true + + true + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_io/.project b/ros2_ws/src/ecl_lite/ecl_io/.project new file mode 100644 index 0000000..cd4ff79 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/.project @@ -0,0 +1,79 @@ + + + ecl_io + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_io/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_io/.settings/language.settings.xml new file mode 100644 index 0000000..b7e4cd3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_io/.settings/org.eclipse.cdt.codan.core.prefs b/ros2_ws/src/ecl_lite/ecl_io/.settings/org.eclipse.cdt.codan.core.prefs new file mode 100644 index 0000000..77496f5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/.settings/org.eclipse.cdt.codan.core.prefs @@ -0,0 +1,75 @@ +eclipse.preferences.version=1 +org.eclipse.cdt.codan.checkers.errnoreturn=Warning +org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return\\")",implicit\=>false} +org.eclipse.cdt.codan.checkers.errreturnvalue=Error +org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused return value\\")"} +org.eclipse.cdt.codan.checkers.nocommentinside=-Error +org.eclipse.cdt.codan.checkers.nocommentinside.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Nesting comments\\")"} +org.eclipse.cdt.codan.checkers.nolinecomment=-Error +org.eclipse.cdt.codan.checkers.nolinecomment.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Line comments\\")"} +org.eclipse.cdt.codan.checkers.noreturn=Error +org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return value\\")",implicit\=>false} +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=Error +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Abstract class cannot be instantiated\\")"} +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=Error +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Ambiguous problem\\")"} +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment in condition\\")"} +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment to itself\\")"} +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No break at end of case\\")",no_break_comment\=>"no break",last_case_param\=>false,empty_case_param\=>false,enable_fallthrough_quickfix_param\=>false} +org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning +org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Catching by reference is recommended\\")",unknown\=>false,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=Error +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Circular inheritance\\")"} +org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=Warning +org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class members should be properly initialized\\")",skip\=>true} +org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem=Error +org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid 'decltype(auto)' specifier\\")"} +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Field cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Function cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.InvalidArguments=Error +org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid arguments\\")"} +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=Error +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid template argument\\")"} +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=Error +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Label statement not found\\")"} +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=Error +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Member declaration not found\\")"} +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Method cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Name convention for function\\")",pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class has a virtual method and non-virtual destructor\\")"} +org.eclipse.cdt.codan.internal.checkers.OverloadProblem=Error +org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid overload\\")"} +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=Error +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redeclaration\\")"} +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=Error +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redefinition\\")"} +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Return with parenthesis\\")"} +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Format String Vulnerability\\")"} +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Statement has no effect\\")",macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suggested parenthesis around expression\\")",paramNot\=>false} +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suspicious semicolon\\")",else\=>false,afterelse\=>false} +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Type cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused function declaration\\")",macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused static function\\")",macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused variable declaration in file scope\\")",macro\=>true,exceptions\=>("@(\#)","$Id")} +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Error +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Symbol is not resolved\\")"} +org.eclipse.cdt.qt.core.qtproblem=Warning +org.eclipse.cdt.qt.core.qtproblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_ON_FILE_OPEN\=>true,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>null} diff --git a/ros2_ws/src/ecl_lite/ecl_io/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_io/CHANGELOG.rst new file mode 100644 index 0000000..abd4059 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/CHANGELOG.rst @@ -0,0 +1,8 @@ +========= +Changelog +========= + +0.61.6 (2016-06-16) +------------------- + +* accomodate platforms (e.g. macosx) without SOCK_NONBLOCK diff --git a/ros2_ws/src/ecl_lite/ecl_io/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/CMakeLists.txt new file mode 100644 index 0000000..36a5e12 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/CMakeLists.txt @@ -0,0 +1,68 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_io) + +############################################################################## +# Sockets +############################################################################## + +set(sockets_INCLUDE_DIRS "") # Just assume they're in the system dirs for now +if(MINGW) + set(sockets_LIBRARIES rpcrt4 shell32 ws2_32 advapi32 kernel32 msvcrt) +elseif(WIN32) + find_library(sockets_LIBRARIES ws2_32) +else() + set(sockets_LIBRARIES "") +endif() + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +include_directories(include + ${ecl_config_INCLUDE_DIRS} + ${ecl_errors_INCLUDE_DIRS} + ) + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors +) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..bbc4d7a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(io) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io.hpp b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io.hpp new file mode 100644 index 0000000..14b4a3a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io.hpp @@ -0,0 +1,24 @@ +/** + * @file include/ecl/io.hpp + * + * @brief Collects headers for ecl_io. + * + * @date Jan 1970 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SOCKETS_HPP_ +#define ECL_SOCKETS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "io/macros.hpp" +#include "io/sockets.hpp" +#include "io/socketpair.hpp" +#include "io/poll.hpp" + +#endif /* ECL_SOCKETS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/CMakeLists.txt new file mode 100644 index 0000000..3c5b313 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/sockets) diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/macros.hpp b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/macros.hpp new file mode 100644 index 0000000..2520c99 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/macros.hpp @@ -0,0 +1,33 @@ +/** + * @file /include/ecl/io/macros.hpp + * + * @brief Macros for windows dlls. + * + * @date March 2013. + **//***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IO_MACROS_HPP_ +#define ECL_IO_MACROS_HPP_ + +/***************************************************************************** +** PreProcessing +*****************************************************************************/ +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_io_EXPORTS // we are building a shared lib/dll + #define ecl_io_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_io_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_io_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_io_PUBLIC + #define ecl_io_LOCAL +#endif + + +#endif /* ECL_IO_MACROS_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/poll.hpp b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/poll.hpp new file mode 100644 index 0000000..e7bc5c9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/poll.hpp @@ -0,0 +1,96 @@ +/** + * @file /ecl_io/include/ecl/io/poll.hpp + * + * @brief Cross platform api for a polling method. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IO_POLL_HPP_ +#define ECL_IO_POLL_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "sockets.hpp" + +#ifdef ECL_IS_WIN32 + // nothing special here. +#else + #include +#endif + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#ifdef ECL_IS_WIN32 + #ifndef POLLRDNORM + #define POLLRDNORM 0x0100 /* mapped to read fds_set */ + #endif + #ifndef POLLRDBAND + #define POLLRDBAND 0x0200 /* mapped to exception fds_set */ + #endif + #ifndef POLLIN + #define POLLIN (POLLRDNORM | POLLRDBAND) /* There is data to read. */ + #endif + #ifndef POLLPRI + #define POLLPRI 0x0400 /* There is urgent data to read. */ + #endif + + #ifndef POLLWRNORM + #define POLLWRNORM 0x0010 /* mapped to write fds_set */ + #endif + #ifndef POLLOUT + #define POLLOUT (POLLWRNORM) /* Writing now will not block. */ + #endif + #ifndef POLLWRBAND + #define POLLWRBAND 0x0020 /* mapped to write fds_set */ + #endif + #ifndef POLLERR + #define POLLERR 0x0001 /* Error condition. */ + #endif + #ifndef POLLHUP + #define POLLHUP 0x0002 /* Hung up. */ + #endif + #ifndef POLLNVAL + #define POLLNVAL 0x0004 /* Invalid polling request. */ + #endif +#else + // Nothing to see here! +#endif + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Types +*****************************************************************************/ + +#ifdef ECL_IS_WIN32 + /* poll emulation support */ + typedef struct socket_pollfd { + socket_descriptor fd; /* file descriptor */ + short events; /* requested events */ + short revents; /* returned events */ + } socket_pollfd; + + typedef unsigned long int nfds_t; +#else + typedef struct pollfd socket_pollfd; + typedef ::nfds_t ndfs_t; +#endif + + + ecl_io_PUBLIC int poll_sockets(socket_pollfd *fds, nfds_t nfds, int timeout); + +} // namespace ecl + +#endif /* ECL_IO_POLL_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/socketpair.hpp b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/socketpair.hpp new file mode 100644 index 0000000..d77eea6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/socketpair.hpp @@ -0,0 +1,45 @@ +/** + * @file /ecl_io/include/ecl/io/socketpair.hpp + * + * @brief Extends socketpair functionality to windows. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_IO_SOCKETPAIR_HPP_ +#define ECL_IO_SOCKETPAIR_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "sockets.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +/** + * @brief Creates a socket pair internal to the current process. + * + * Valid return values are quite simplified. On posix they'll return a variety of + * arguments similar to the posix return values, on windows it will only + * return ConfigurationError if something went wrong. This can be expanded + * in further detail if necessary. + * + * @param socket_fd_pair : pair of file descriptors for the sockets to be opened. + * @param non_blocking : set the pair to be non-blocking(true) or blocking (false). + * + * @return SocketError : error return value. + */ +ecl_io_PUBLIC SocketError socketpair(socket_descriptor socket_fd_pair[2], const bool non_blocking = false ); + + +} // namespace ecl + +#endif /* ECL_IO_SOCKETPAIR_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/sockets.hpp b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/sockets.hpp new file mode 100644 index 0000000..1f73a36 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/include/ecl/io/sockets.hpp @@ -0,0 +1,158 @@ +/** + * @file /ecl_io/include/ecl/io/sockets.hpp + * + * @brief Cross platform socket api. + * + * Winsock references: + * + * Getting Started + * - http://msdn.microsoft.com/en-us/library/ms738545%28v=vs.85%29.aspx + * Error Codes + * - http://msdn.microsoft.com/en-us/library/ms740668%28VS.85%29.aspx + * + * @date February 2011. + **/ +/***************************************************************************** + ** Ifdefs + *****************************************************************************/ + +#ifndef ECL_IO_SOCKETS_HPP_ +#define ECL_IO_SOCKETS_HPP_ + +/***************************************************************************** + ** Include + *****************************************************************************/ + +#include +#include +#include + +#ifdef ECL_IS_WIN32 + #include + #include + #include + // #include + // #include +#elif defined(ECL_IS_POSIX) + #include // provides AF_LOCAL etc... + #include +#else + #error("There is not a supporting sockets implementation on this platform (possibly needs extended ecl support).") +#endif +#include "macros.hpp" + +/***************************************************************************** + ** Namespaces + *****************************************************************************/ + +namespace ecl +{ + +/***************************************************************************** + ** Types + *****************************************************************************/ + +#ifdef ECL_IS_WIN32 + typedef SOCKET socket_descriptor; /**< @brief Cross-platform typedef for a socket file descriptor. **/ +#else + typedef int socket_descriptor; /**< @brief Cross-platform typedef for a socket file descriptor. **/ +#endif + +/***************************************************************************** + ** Errors + *****************************************************************************/ + +/** + * @brief Extends the generic error handler with socket specific error strings. + */ +class ecl_io_PUBLIC SocketError : public Error +{ +public: + /** + * @brief Configures the error class with the specified error flag. + * + * @param flag : the error type. + */ + SocketError(const ErrorFlag& flag = UnknownError) : Error(flag) + {} +protected: + virtual const char* invalidArgErrorString() const + { return "One of the arguments is invalid (usually a socket descriptor).";} +#ifdef ECL_IS_WIN32 + virtual const char* notSupportedError() const + { return "This version of winsock is not supported on this platform.";} + virtual const char* interruptedErrorString() const + { return "Interrupted by WSACancelBlockingCall.";} + virtual const char* notInitialisedErrorString() const + { return "The underlying winsock subsystem is not initialised (needs WSAStartup).";} + virtual const char* blockingErrorString() const + { return "Marked as non-blocking, but current configuration would block.";} + virtual const char* busyErrorString() const + { return "A blocking winsock operation is in progress.";} + virtual const char* systemFailureErrorString() const + { return "The network subsystem has failed.";} +#elif defined(ECL_IS_POSIX) + virtual const char* interruptedErrorString() const + { return "Interrupted by a signal or an io error.";} + virtual const char* argNotSupportedString() const + { return "The specified address family or protocol is not supported on this machine.";} +#endif +}; + +/***************************************************************************** + ** Functions + *****************************************************************************/ + +/** + * @brief Initialise the socket subsystem. + * + * Usually only needed on windows. + * + * Valid return values: + * + * - NoError, + * - NotInitialisedError (win), + * - NotSupportedError (win), + * - BusyError (win), + * - OutOfResourcesError (win), + * - InvalidArgError (win). + * + * @return SocketError : error return value. + */ +ecl_io_PUBLIC SocketError init_sockets(); +/** + * @brief Close a socket. + * + * Cross platform api for closing a socket. + * + * Valid return values: + * + * - NoError, + * - InvalidArgError, + * - InterruptedError, + * - NotInitialisedError (win), + * - SystemFailureError (win), + * - BlockingError (win). + * + * @return SocketError : error return value. + */ +ecl_io_PUBLIC SocketError close_socket(const socket_descriptor& sock); +/** + * @brief Shutdown the socket subsystem. + * + * Usually only needed on windows. + * + * Valid return values: + * + * - NoError, + * - NotInitialisedError (win), + * - SystemFailureError (win), + * - BusyError (win). + * + * @return SocketError : error return value. + */ +ecl_io_PUBLIC SocketError shutdown_sockets(); + +} // namespace ecl + +#endif /* ECL_IO_SOCKETS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_io/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_io/mainpage.dox new file mode 100644 index 0000000..57a2256 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/mainpage.dox @@ -0,0 +1,55 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This package provides cross platform api to some of the lower level + socket functions available on different platforms. Currently there is + only minor support for a few functions on: + + - Windows + - Posix + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Cross platform functions + using ecl::init_sockets; + using ecl::shutdown_sockets; + using ecl::poll_sockets; + using ecl::close_socket; + using ecl::socket_pair; + @endcode + + You will also need to link to -lecl_io. + +\section library Library + + - init_sockets() : initialises winsock on windows. + - shutdown_sockets() : shuts down winsock on windows. + - poll_sockets() : a drop in for the posix poll function on windoze. + - socketpair() : a drop in for the posix socketpair function on windoze. + - close_socket() : standardises the api for closing a socket. + + A drop in for poll() on windoze is soon to come. + +\section utilities Examples + + Really rough, no tests yet, just some examples. + + - src/examples/poll.cpp : tests the basic sockets api. + - src/examples/sockets.cpp : tests the basic sockets api. + - src/examples/socketpair.cpp : tests the socketpair drop-in for windows. + +\section ChangeLog + + - Feb 11 : a drop-in for the socketpair function added for windows. + - Jan 11 : simple cross platform types and api added. + +*/ \ No newline at end of file diff --git a/ros2_ws/src/ecl_lite/ecl_io/package.xml b/ros2_ws/src/ecl_lite/ecl_io/package.xml new file mode 100644 index 0000000..2623080 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/package.xml @@ -0,0 +1,31 @@ + + + ecl_io + 1.2.0 + + Most implementations (windows, posix, ...) have slightly different api for + low level input-output functions. These are gathered here and re-represented + with a cross platform set of functions. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_io + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_license + ecl_config + ecl_errors + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/src/CMakeLists.txt new file mode 100644 index 0000000..a9c0ba6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(lib) +add_subdirectory(examples) diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/src/examples/CMakeLists.txt new file mode 100644 index 0000000..bc6bc41 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/examples/CMakeLists.txt @@ -0,0 +1,22 @@ +############################################################################### +# Macro +############################################################################### + +macro(ecl_io_add_example name) + set(target_name ecl_io_example_${name}) + add_executable(${target_name} ${name}.cpp) + target_link_libraries(${target_name} + ${PROJECT_NAME} + ${sockets_LIBRARIES} + ) + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME demo_${name}) + install(TARGETS ${target_name} RUNTIME DESTINATION lib/${PROJECT_NAME}) +endmacro() + +############################################################################## +# Examples +############################################################################## + +ecl_io_add_example(sockets sockets.cpp) +ecl_io_add_example(socketpair socketpair.cpp) +ecl_io_add_example(poll poll.cpp) diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/examples/poll.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/examples/poll.cpp new file mode 100644 index 0000000..5193aaa --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/examples/poll.cpp @@ -0,0 +1,143 @@ +/** + * @file /ecl_io/src/examples/poll.cpp + * + * @brief Test the cross platform poll implementation. + * + * @date February 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/io/poll.hpp" +#include "../../include/ecl/io/socketpair.hpp" +#ifndef ECL_IS_WIN32 + #include +#endif + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#define DATA1 "In Xanadu, did Kublai Khan . . ." +#define DATA2 "A stately pleasure dome decree . . ." + +/***************************************************************************** +** Globals +*****************************************************************************/ + +ecl::socket_descriptor socket_pair[2]; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +int socket_error() { +#ifdef ECL_IS_WIN32 + return WSAGetLastError(); +#else + return errno; +#endif +} + +void sleep_one_sec() { +#ifdef ECL_IS_WIN32 + Sleep(1000); +#else + sleep(1); +#endif +} + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + ecl::SocketError error = ecl::init_sockets(); + if ( error.flag() != ecl::NoError ) { + std::cout << error.what() << std::endl; + abort(); + } + + // non blocking mode - need it so the read's don't block below. + error = ecl::socketpair(socket_pair,true); + + if ( error.flag() != ecl::NoError) { + std::cout << error.what() << std::endl; + std::cout << "SocketPair Error: " << socket_error() << std::endl; + abort(); + } + ecl::socket_pollfd pfd[2]; + pfd[0].fd = socket_pair[0]; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + pfd[1].fd = socket_pair[1]; + pfd[1].events = POLLIN; + pfd[1].revents = 0; + + int poll_timeout = 500; // ms + int result = 0; + unsigned int count = 0; + while ( count < 10 ) { + if((result = ecl::poll_sockets(pfd, 2, poll_timeout)) < 0) { + std::cout << socket_error(); + } else if ( result > 0 ) { + char receiving_buffer[256]; + int n; + for ( unsigned int i = 0; i < 2; ++i ) { + if ( pfd[i].revents == POLLIN ) { +#ifdef ECL_IS_WIN32 + while ( ( n = ::recv(socket_pair[i], reinterpret_cast(receiving_buffer), 256, 0) ) > 0 ) { +#else + while( (n = read(socket_pair[i], receiving_buffer, 256)) > 0) { +#endif + std::cout << receiving_buffer << std::endl; + if ( i == 0 ) { +#ifdef ECL_IS_WIN32 + if( ::send(socket_pair[0], reinterpret_cast(DATA1), sizeof(DATA1), 0) < 0 ) { +#else + if (write(socket_pair[0], DATA1, sizeof(DATA1)) < 0) { +#endif + std::cerr << "Failed to write to the socket." << std::endl; + } + } else { +#ifdef ECL_IS_WIN32 + if( ::send(socket_pair[1], reinterpret_cast(DATA2), sizeof(DATA2), 0) < 0 ) { +#else + if (write(socket_pair[1], DATA2, sizeof(DATA2)) < 0) { +#endif + std::cerr << "Failed to write to the socket." << std::endl; + } + } + }; + pfd[i].revents = 0; + } + } + sleep_one_sec(); + } else { + // it will pass through here once to kickstart things +#ifdef ECL_IS_WIN32 + if( ::send(socket_pair[0], reinterpret_cast(DATA1), sizeof(DATA1), 0) < 0 ) { +#else + if (write(socket_pair[0], DATA1, sizeof(DATA1)) < 0) { +#endif + std::cerr << "Failed to write to the socket." << std::endl; + } + sleep_one_sec(); + } + ++count; + } + + + ecl::close_socket(socket_pair[0]); + ecl::close_socket(socket_pair[1]); + + return 0; +} + + diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/examples/socketpair.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/examples/socketpair.cpp new file mode 100644 index 0000000..7c6a601 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/examples/socketpair.cpp @@ -0,0 +1,146 @@ +/** + * @file src/examples/socketpair.cpp + * + * @brief Example code for a socket pair. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#ifndef ECL_IS_WIN32 + #include +#endif +#include +#include "../../include/ecl/io/socketpair.hpp" + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#define DATA1 "In Xanadu, did Kublai Khan . . ." +#define DATA2 "A stately pleasure dome decree . . ." + +/***************************************************************************** +** Globals +*****************************************************************************/ + +ecl::socket_descriptor socket_pair[2]; + +/***************************************************************************** +** Functions +*****************************************************************************/ + +#ifdef ECL_IS_WIN32 +DWORD WINAPI f(LPVOID args) { + char buf[1024]; + /* This is the child. */ + while ( 1 ) { + if( ::send(socket_pair[1], reinterpret_cast(DATA1), sizeof(DATA1), 0) < 0 ) { + std::cerr << "Failed to write to the threaded socket." << std::endl; + } + if ( ::recv(socket_pair[1], reinterpret_cast(buf), 1024, 0) < 0 ) { + std::cerr << "Failed to read from the threaded socket." << std::endl; + } else { + std::cout << buf << std::endl; + } + Sleep(1000); + } + return 0; +} +#endif + +int socket_error() { +#ifdef ECL_IS_WIN32 + return WSAGetLastError(); +#else + return errno; +#endif +} +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + ecl::SocketError error = ecl::init_sockets(); + if ( error.flag() != ecl::NoError ) { + std::cout << error.what() << std::endl; + abort(); + } + + // blocking mode + error = ecl::socketpair(socket_pair); + // non blocking mode + // error = ecl::socketpair(socket_pair,true); + + if ( error.flag() != ecl::NoError) { + std::cout << error.what() << std::endl; + std::cout << "SocketPair Error: " << socket_error() << std::endl; + abort(); + } + char buf[1024]; +#ifdef ECL_IS_WIN32 + DWORD id; + char thread_param[3]; + HANDLE thread_handle = CreateThread( + NULL, // default security attributes + 0, // use default stack size + f, // thread function name + &thread_param, // argument to thread function + 0, // use default creation flags + &id // returns the thread identifier + ); + /* This is the parent */ + while ( 1 ) { + if ( ::recv(socket_pair[0], reinterpret_cast(buf), 1024, 0) < 0 ) { + std::cerr << "Failed to read from the main socket." << std::endl; + } else { + std::cout << buf << std::endl; + } + if( ::send(socket_pair[0], reinterpret_cast(DATA2), sizeof(DATA2), 0) < 0 ) { + std::cerr << "Failed to write to the main socket." << std::endl; + } + Sleep(1000); + } +#else + int child; + if ((child = fork()) == -1) { + std::cerr << "Failed to fork." << std::endl; + } else if (child) { + /* This is the parent */ + while ( 1 ) { + if (read(socket_pair[0], buf, 1024) < 0) { + std::cerr << "Failed to read from the socket." << std::endl; + } else { + std::cout << buf << std::endl; + } + if (write(socket_pair[0], DATA2, sizeof(DATA2)) < 0) { + std::cerr << "Failed to write to the socket." << std::endl; + } + sleep(1); + } + } else { + /* This is the child. */ + while ( 1 ) { + if (write(socket_pair[1], DATA1, sizeof(DATA1)) < 0) { + std::cerr << "Failed to write to the socket." << std::endl; + } + if (read(socket_pair[1], buf, 1024) < 0) { + std::cerr << "Failed to read from the socket." << std::endl; + } else { + std::cout << buf << std::endl; + } + sleep(1); // 1 sec + } + } +#endif + ecl::close_socket(socket_pair[0]); + ecl::close_socket(socket_pair[1]); + return 0; +} diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/examples/sockets.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/examples/sockets.cpp new file mode 100644 index 0000000..74f96b1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/examples/sockets.cpp @@ -0,0 +1,35 @@ +/** + * @file src/examples/sockets.cpp + * + * @brief Test the select implementation on different platforms. + * + * - http://www.gnu.org/s/libc/manual/html_node/Server-Example.html#Server-Example + * - make socket example + * + * http://www.gnu.org/s/libc/manual/html_node/Inet-Example.html#Inet-Example + * @date February, 2011. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/io/sockets.hpp" + +/***************************************************************************** +** Main program +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + ecl::SocketError error = ecl::init_sockets(); + if ( error.flag() != ecl::NoError ) { + std::cout << error.what() << std::endl; + } else { + std::cout << "Socket subsystem started up sucessfully." << std::endl; + } +// ecl::sockets::socket_descriptor = socket(AF_INET, SOCK_STREAM, 0); + + return 0; +} diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_io/src/lib/CMakeLists.txt new file mode 100644 index 0000000..5ab0d8d --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/lib/CMakeLists.txt @@ -0,0 +1,34 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) +target_include_directories( + ${PROJECT_NAME} + PUBLIC + $ + $ +) +target_link_libraries(${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors + ${sockets_LIBRARIES} +) +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/lib/poll.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/lib/poll.cpp new file mode 100644 index 0000000..86743f6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/lib/poll.cpp @@ -0,0 +1,155 @@ +/** + * @file /ecl_io/src/lib/poll.cpp + * + * @brief Implementation for a cross platform polling function. + * + * @date February 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/io/poll.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementation +*****************************************************************************/ + +int poll_sockets(socket_pollfd *fds, nfds_t nfds, int timeout) { +#if defined(ECL_IS_WIN32) + fd_set readfds, writefds, exceptfds; + struct timeval tv, *ptv; + socket_descriptor max_fd; + int rc; + nfds_t i; + + if (fds == NULL) { + errno = EFAULT; + return -1; + } + + FD_ZERO (&readfds); + FD_ZERO (&writefds); + FD_ZERO (&exceptfds); + + /********************* + ** Compute fd sets + **********************/ + // also find the largest descriptor. + for (rc = -1, max_fd = 0, i = 0; i < nfds; i++) { + if (fds[i].fd == INVALID_SOCKET) { + continue; + } + if (fds[i].events & (POLLIN | POLLRDNORM)) { + FD_SET (fds[i].fd, &readfds); + } + if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) { + FD_SET (fds[i].fd, &writefds); + } + if (fds[i].events & (POLLPRI | POLLRDBAND)) { + FD_SET (fds[i].fd, &exceptfds); + } + if (fds[i].fd > max_fd && + (fds[i].events & (POLLIN | POLLOUT | POLLPRI | + POLLRDNORM | POLLRDBAND | + POLLWRNORM | POLLWRBAND))) { + max_fd = fds[i].fd; + rc = 0; + } + } + + if (rc == -1) { + errno = EINVAL; + return -1; + } + /********************* + ** Setting the timeout + **********************/ + if (timeout < 0) { + ptv = NULL; + } else { + ptv = &tv; + if (timeout == 0) { + tv.tv_sec = 0; + tv.tv_usec = 0; + } else { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + } + } + + rc = select (max_fd + 1, &readfds, &writefds, &exceptfds, ptv); + if (rc < 0) { + return -1; + } else if ( rc == 0 ) { + return 0; + } + + for (rc = 0, i = 0; i < nfds; i++) { + if (fds[i].fd != INVALID_SOCKET) { + fds[i].revents = 0; + + if (FD_ISSET(fds[i].fd, &readfds)) { + int save_errno = errno; + char data[64] = {0}; + int ret; + + /* support for POLLHUP */ + // just check if there's incoming data, without removing it from the queue. + ret = recv(fds[i].fd, data, 64, MSG_PEEK); + #ifdef WIN32 + if ((ret == -1) && + (errno == WSAESHUTDOWN || errno == WSAECONNRESET || + (errno == WSAECONNABORTED) || errno == WSAENETRESET)) + #else + if ((ret == -1) && + (errno == ESHUTDOWN || errno == ECONNRESET || + (errno == ECONNABORTED) || errno == ENETRESET)) + #endif + { + fds[i].revents |= POLLHUP; + } else { + fds[i].revents |= fds[i].events & (POLLIN | POLLRDNORM); + } + errno = save_errno; + } + if (FD_ISSET(fds[i].fd, &writefds)) { + fds[i].revents |= fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND); + } + + if (FD_ISSET(fds[i].fd, &exceptfds)) { + fds[i].revents |= fds[i].events & (POLLPRI | POLLRDBAND); + } + + if (fds[i].revents & ~POLLHUP) { + rc++; + } + } else { + fds[i].revents = POLLNVAL; + } + } + return rc; +#else + // should really put in a cmake check to check that the poll function is present + // --> do it when necessary. + + // use an existing poll implementation + int result = poll(fds, nfds, timeout); + if ( result < 0 ) { + // EINTR means that we got interrupted by a signal, and is not an error + if(errno == EINTR) { + result = 0; + } + } + return result; +#endif // poll_sockets functions +} + +} // namespace ecl diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/lib/socketpair.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/lib/socketpair.cpp new file mode 100644 index 0000000..86367eb --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/lib/socketpair.cpp @@ -0,0 +1,301 @@ +/** + * @file /ecl_io/src/lib/socketpair.cpp + * + * @brief Crossplatform implementation for generating a local socket pair. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/io/socketpair.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +SocketError socketpair(socket_descriptor socket_fd_pair[2], const bool non_blocking) { +#ifdef ECL_IS_WIN32 + + union { + struct sockaddr_in inaddr; + struct sockaddr addr; + } a; + socklen_t addrlen = sizeof(a.inaddr); + + /********************* + ** Listener + **********************/ + socket_descriptor listen_socket = INVALID_SOCKET; + listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listen_socket == INVALID_SOCKET) { + return SocketError(ConfigurationError); + } + + // allow it to be bound to an address already in use - do we actually need this? + int reuse = 1; + if (setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &reuse, (socklen_t) sizeof(reuse)) == SOCKET_ERROR ) { + ::closesocket(listen_socket); + return SocketError(ConfigurationError); + } + + memset(&a, 0, sizeof(a)); + a.inaddr.sin_family = AF_INET; + a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + // For TCP/IP, if the port is specified as zero, the service provider assigns + // a unique port to the application from the dynamic client port range. + a.inaddr.sin_port = 0; + + if (bind(listen_socket, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) { + ::closesocket(listen_socket); + return SocketError(ConfigurationError); + } + // we need this below because the system auto filled in some entries, e.g. port # + if (getsockname(listen_socket, &a.addr, &addrlen) == SOCKET_ERROR) { + ::closesocket(listen_socket); + return SocketError(ConfigurationError); + } + // max 1 connection permitted + if (listen(listen_socket, 1) == SOCKET_ERROR) { + ::closesocket(listen_socket); + return SocketError(ConfigurationError); + } + /********************* + ** Connection + **********************/ + // initialise + socket_fd_pair[0] = socket_fd_pair[1] = INVALID_SOCKET; + // create first socket and connect to the listener + // DWORD flags = (make_overlapped ? WSA_FLAG_OVERLAPPED : 0); + DWORD overlapped_flag = 0; + socket_fd_pair[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, overlapped_flag); + if (socket_fd_pair[0] == INVALID_SOCKET) { + ::closesocket(listen_socket); + ::closesocket(socket_fd_pair[0]); + return SocketError(ConfigurationError); + } + // reusing the information from above to connect to the listener + if (connect(socket_fd_pair[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) { + ::closesocket(listen_socket); + ::closesocket(socket_fd_pair[0]); + return SocketError(ConfigurationError); + } + /********************* + ** Accept + **********************/ + socket_fd_pair[1] = accept(listen_socket, NULL, NULL); + if (socket_fd_pair[1] == INVALID_SOCKET) { + ::closesocket(listen_socket); + ::closesocket(socket_fd_pair[0]); + ::closesocket(socket_fd_pair[1]); + return SocketError(ConfigurationError); + } + /********************* + ** Nonblocking + **********************/ + // should we do this or should we set io overlapping? + unsigned long non_blocking_flag = 0; // by default is blocking. + if ( non_blocking ) { + non_blocking_flag = 1; + if(ioctlsocket( socket_fd_pair[0], FIONBIO, &non_blocking_flag ) != 0 ) { + ::closesocket(listen_socket); + ::closesocket(socket_fd_pair[0]); + ::closesocket(socket_fd_pair[1]); + return SocketError(ConfigurationError); + } + if(ioctlsocket( socket_fd_pair[1], FIONBIO, &non_blocking_flag ) != 0 ) { + ::closesocket(listen_socket); + ::closesocket(socket_fd_pair[0]); + ::closesocket(socket_fd_pair[1]); + return SocketError(ConfigurationError); + } + } + /********************* + ** Cleanup + **********************/ + // the listener has done its job. + ::closesocket(listen_socket); + +#else + // returns 0 on success, -1 and errno otherwise + int result = 0; + if ( non_blocking ) { +#if defined(SOCK_NONBLOCK) + result = ::socketpair(AF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0, socket_fd_pair); +#else + result = ::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fd_pair); + // TODO: SOCK_NONBLOCK is n/a at least on macosx -> figure out how to make it non-blocking +#endif + } else { + ::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fd_pair); + } + if (result < 0) { + switch(errno) { + case (EAFNOSUPPORT) : { return SocketError(ArgNotSupportedError); } // AF_LOCAL is not supported + case (EFAULT) : { return SocketError(MemoryError); } + case (EMFILE) : { return SocketError(OutOfResourcesError); } + case (ENFILE) : { return SocketError(OutOfResourcesError); } + case (EOPNOTSUPP) : { return SocketError(ArgNotSupportedError); } + case (EPROTONOSUPPORT) : { return SocketError(ArgNotSupportedError); } + default : { return SocketError(UnknownError); } + } + } +#endif + return SocketError(NoError); +} + +} // namespace ecl + + + + +/***************************************************************************** +** Graveyard +*****************************************************************************/ + +// /********************* +// ** Notes +// **********************/ +// // Using port 21 - is this a problem always using this port? +// +// /****************************************** +// ** Server +// *******************************************/ +// struct addrinfo *result = NULL, *ptr = NULL, hints; +// +// // windows sockets can't do AF_LOCAL +// ZeroMemory(&hints, sizeof (hints)); +// hints.ai_family = AF_INET; +// hints.ai_socktype = SOCK_STREAM; +// hints.ai_protocol = IPPROTO_TCP; +// // AI_PASSIVE flag indicates the caller intends to use the +// // returned socket address structure in a call to the bind function. +// // When the AI_PASSIVE flag is set and nodename parameter to the +// // getaddrinfo function is a NULL pointer, the IP address portion +// // of the socket address structure is set to INADDR_ANY for IPv4 +// // addresses or IN6ADDR_ANY_INIT for IPv6 addresses. +// hints.ai_flags = AI_PASSIVE; +// +// // Resolve the local address and port to be used by the server +// // first argument is the nodename parameter as described above. +// int wsock_error = getaddrinfo(NULL, "21", &hints, &result); +// if (wsock_error != 0) { +// return SocketError(ConfigurationError); +// } +// +// /********************* +// ** Server Socket +// **********************/ +// socket_descriptor listen_socket = INVALID_SOCKET; +// // Create a SOCKET for the server to listen for client connections +// listen_socket = ::socket(result->ai_family, result->ai_socktype, result->ai_protocol); +// if (listen_socket == INVALID_SOCKET) { +// freeaddrinfo(result); +// return SocketError(ConfigurationError); +// } +// +// /********************* +// ** Bind Server +// **********************/ +// // Bind server to an address. +// wsock_error = bind( listen_socket, result->ai_addr, (int)result->ai_addrlen); +// if (wsock_error == SOCKET_ERROR) { +// freeaddrinfo(result); +// ::closesocket(listen_socket); +// return SocketError(ConfigurationError); +// } +// freeaddrinfo(result); +// +// /********************* +// ** Listen for client +// **********************/ +// if ( listen( listen_socket, SOMAXCONN ) == SOCKET_ERROR ) { +// closesocket(listen_socket); +// return SocketError(ConfigurationError); +// } +// socket_fd_pair[0] = INVALID_SOCKET; +// +// /****************************************** +// ** Client +// *******************************************/ +// ZeroMemory( &hints, sizeof(hints) ); +// hints.ai_family = AF_UNSPEC; +// hints.ai_socktype = SOCK_STREAM; +// hints.ai_protocol = IPPROTO_TCP; +// // Resolve the server address and port +// wsock_error = getaddrinfo("localhost", "21", &hints, &result); +// if (wsock_error != 0) { +// ::closesocket(listen_socket); +// return SocketError(ConfigurationError); +// } +// socket_fd_pair[1] = INVALID_SOCKET; +// +// /********************* +// ** Create client +// **********************/ +// ptr=result; +// socket_fd_pair[1] = ::socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); +// if (socket_fd_pair[1] == INVALID_SOCKET) { +// ::closesocket(listen_socket); +// freeaddrinfo(result); +// return SocketError(ConfigurationError); +// } +// +// /********************* +// ** Connect to server +// **********************/ +// wsock_error = connect( socket_fd_pair[1], ptr->ai_addr, (int)ptr->ai_addrlen); +// if (wsock_error == SOCKET_ERROR) { +// ::closesocket(listen_socket); +// closesocket(socket_fd_pair[1]); +// socket_fd_pair[1] = INVALID_SOCKET; +// return SocketError(ConfigurationError); +// } +// +// // Should really try the next address returned by getaddrinfo +// // if the connect call failed +// // But for this simple example we just free the resources +// // returned by getaddrinfo and print an error message +// +// freeaddrinfo(result); +// +// if (socket_fd_pair[1] == INVALID_SOCKET) { +// return SocketError(ConfigurationError); +// } +// +// /********************* +// ** Accept connection +// **********************/ +// // Server accepts a client socket +// socket_fd_pair[0] = accept(listen_socket, NULL, NULL); +// if (socket_fd_pair[0] == INVALID_SOCKET) { +// ::closesocket(listen_socket); +// ::closesocket(socket_fd_pair[1]); +// return SocketError(ConfigurationError); +// } +// +// +// /********************* +// ** Nonblocking +// **********************/ +// unsigned long non_blocking_flag = 0; // by default is blocking. +// if ( non_blocking ) { +// non_blocking_flag = 1; +// if(ioctlsocket( socket_fd_pair[0], FIONBIO, &non_blocking_flag ) != 0 ) { +// ::closesocket(listen_socket); +// ::closesocket(socket_fd_pair[0]); +// ::closesocket(socket_fd_pair[1]); +// return SocketError(ConfigurationError); +// } +// if(ioctlsocket( socket_fd_pair[1], FIONBIO, &non_blocking_flag ) != 0 ) { +// ::closesocket(listen_socket); +// ::closesocket(socket_fd_pair[0]); +// ::closesocket(socket_fd_pair[1]); +// return SocketError(ConfigurationError); +// } +// } diff --git a/ros2_ws/src/ecl_lite/ecl_io/src/lib/sockets.cpp b/ros2_ws/src/ecl_lite/ecl_io/src/lib/sockets.cpp new file mode 100644 index 0000000..297bacb --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_io/src/lib/sockets.cpp @@ -0,0 +1,89 @@ +/** + * @file /ecl_io/src/lib/sockets.cpp + * + * @brief Initialising a socket subsystem. + * + * @date February 2011. + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#ifndef ECL_IS_WIN32 + #include +#endif +#include +#include "../../include/ecl/io/sockets.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +SocketError init_sockets(void) { +#ifdef ECL_IS_WIN32 + static bool already_initialised = false; + if ( !already_initialised ) { + struct WSAData wsaData; + int err; + /* Initialises use of the Winsock DLL subsystem. */ + if ( (err = WSAStartup(MAKEWORD(2, 0), &wsaData)) != 0) { + switch( WSAGetLastError() ) { + case(WSASYSNOTREADY) : { return SocketError(NotInitialisedError); } + case(WSAVERNOTSUPPORTED) : { return SocketError(NotSupportedError); } + case(WSAEINPROGRESS) : { return SocketError(BusyError); } + case(WSAEPROCLIM) : { return SocketError(OutOfResourcesError); } + case(WSAEFAULT) : { return SocketError(InvalidArgError); } + default : { return SocketError(UnknownError); } + } + } + } +#endif + return SocketError(NoError); +} + +SocketError close_socket(const socket_descriptor& socket) { +#if defined(ECL_IS_WIN32) + if ( ::closesocket(socket) == SOCKET_ERROR ) { + switch(WSAGetLastError()) { + case(WSANOTINITIALISED) : { return SocketError(NotInitialisedError); } + case(WSAENETDOWN) : { return SocketError(SystemFailureError); } + case(WSAENOTSOCK) : { return SocketError(InvalidArgError); } + case(WSAEINTR) : { return SocketError(InterruptedError); } + case(WSAEWOULDBLOCK) : { return SocketError(BlockingError); } + default : { return SocketError(UnknownError); } + } + } +#elif defined(ECL_IS_POSIX) + if ( ::close(socket) != 0 ) { + switch(errno) { + case(EBADF) : { return SocketError(InvalidArgError); } + case(EINTR) : { return SocketError(InterruptedError); } + case(EIO) : { return SocketError(InterruptedError); } + default : { return SocketError(UnknownError); } + } + } +#endif + return SocketError(NoError); +} + +SocketError shutdown_sockets() { +#ifdef ECL_IS_WIN32 + if ( WSACleanup() == SOCKET_ERROR ) { + switch(WSAGetLastError()) { + case(WSANOTINITIALISED) : { return SocketError(NotInitialisedError); } + case(WSAENETDOWN) : { return SocketError(SystemFailureError); } + case(WSAEINPROGRESS) : { return SocketError(BusyError); } + default : { return SocketError(UnknownError); } + } + } +#endif + return SocketError(NoError); +} + + +} // namespace ecl diff --git a/ros2_ws/src/ecl_lite/ecl_lite/.cproject b/ros2_ws/src/ecl_lite/ecl_lite/.cproject new file mode 100644 index 0000000..93dcfb0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/.cproject @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_lite/.project b/ros2_ws/src/ecl_lite/ecl_lite/.project new file mode 100644 index 0000000..8c997b9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/.project @@ -0,0 +1,79 @@ + + + ecl_lite + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_lite/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_lite/.settings/language.settings.xml new file mode 100644 index 0000000..d930aaf --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_lite/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_lite/CHANGELOG.rst new file mode 100644 index 0000000..42d49a4 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/CHANGELOG.rst @@ -0,0 +1,4 @@ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Changelog for package ecl_lite +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + diff --git a/ros2_ws/src/ecl_lite/ecl_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_lite/CMakeLists.txt new file mode 100644 index 0000000..c0abe9c --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.5) +project(ecl_lite) +find_package(ament_cmake_ros REQUIRED) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_lite/package.xml b/ros2_ws/src/ecl_lite/ecl_lite/package.xml new file mode 100644 index 0000000..0092ba2 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_lite/package.xml @@ -0,0 +1,27 @@ + + + ecl_lite + 1.2.0 + + Libraries and utilities for embedded and low-level linux development. + + Daniel Stonier + Daniel Stonier + BSD + http://www.ros.org/wiki/ecl_lite + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_config + ecl_converters_lite + ecl_errors + ecl_io + ecl_sigslots_lite + ecl_time_lite + + + ament_cmake + + diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.cproject b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.cproject new file mode 100644 index 0000000..8056489 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.cproject @@ -0,0 +1,674 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + + + all + + true + + true + + true + + + + + + make + + + + clean + + true + + true + + true + + + + + + make + + + + examples + + true + + true + + true + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.project b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.project new file mode 100644 index 0000000..8c7b8d0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.project @@ -0,0 +1,79 @@ + + + ecl_sigslots_lite + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.settings/language.settings.xml new file mode 100644 index 0000000..8ba3ae2 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/.settings/language.settings.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CHANGELOG.rst new file mode 100644 index 0000000..01290e6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CHANGELOG.rst @@ -0,0 +1,14 @@ +Release Notes +============= + +Forthcoming +----------- + +1.2.0 (2022-09-27) +------------------ +* [sigslots_lite] new c++14 insists on const expr init in the same translation unit, `#38 `_ + +Pre-Versioning +-------------- +* (2011-03-11) redeisnged to be more self contained +* (2011-02-11) prototype implementation tested diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CMakeLists.txt new file mode 100644 index 0000000..91bdfb5 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/CMakeLists.txt @@ -0,0 +1,71 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_sigslots_lite) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Header Library +############################################################################## + +add_library(${PROJECT_NAME} INTERFACE) +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) +target_link_libraries(${PROJECT_NAME} + INTERFACE + ecl_config::ecl_config + ecl_errors::ecl_errors +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + INCLUDES DESTINATION include +) +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) + +ament_export_dependencies( + ecl_config + ecl_errors +) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..4a6e812 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(sigslots_lite) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite.hpp new file mode 100644 index 0000000..981bd09 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite.hpp @@ -0,0 +1,26 @@ +/** + * @file include/ecl/sigslots_lite.hpp + * + * @brief Collects headers for ecl_sigslots_lite. + * + * @date February 2011. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_HPP_ +#define ECL_SIGSLOTS_LITE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "sigslots_lite/errors.hpp" +#include "sigslots_lite/managers.hpp" +#include "sigslots_lite/slot.hpp" +#include "sigslots_lite/signal.hpp" +#include "sigslots_lite/connect.hpp" +#include "sigslots_lite/utilities.hpp" + +#endif /* ECL_SIGSLOTS_LITE_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/CMakeLists.txt new file mode 100644 index 0000000..624d8d9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/sigslots_lite) diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/connect.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/connect.hpp new file mode 100644 index 0000000..c8f09ca --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/connect.hpp @@ -0,0 +1,178 @@ +/** + * @file include/ecl/sigslots_lite/connect.hpp + * + * @brief Stores functions. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_CONNECT_HPP_ +#define ECL_SIGSLOTS_LITE_CONNECT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "slot.hpp" +#include "signal.hpp" +#include "errors.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { + +/***************************************************************************** +** Privately Used Connects +*****************************************************************************/ + +namespace sigslots { +/** + * @brief Internal worker used to connect a signal with a slot. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError : when the capacity of the signal is exceeded. + * + * @param signal : the signal for connection. + * @param slot : the member slot for connection + */ +template +ecl::lite::sigslots::Error connect(ecl::lite::Signal &signal, MemberSlot &slot) { + return signal.connect(slot); +} + +/** + * @brief Internal worker used to connect a signal with a slot. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError : when the capacity of the signal is exceeded. + * + * @param signal : the signal for connection. + * @param slot : the global slot for connection + */ +template +ecl::lite::sigslots::Error connect(ecl::lite::Signal &signal, GlobalSlot &slot) { + return signal.connect(slot); +} + +} // namespace sigslots + +/***************************************************************************** +** Publicly Used Connects +*****************************************************************************/ + +/** + * @brief Convenience method to connect signal with member function. + * + * This simply passes on the work to Signal's connect method. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError : when the capacity of the member slots or the signal is exceeded. + * + * @param signal : the signal for connection. + * @param f : the member function to slot. + * @param o : the object associated with the member function. + * @return Error : the sigslots error + */ +template +sigslots::Error connect(Signal &signal, void(FunctionClass::*f)(Data), FunctionClass &o) { + // Need to do this just in case o has member slot interfaces for multiple Data types. + // If we don't it can't resolve the footprint that seems to get lost when passing + // the function pointers down the line - another way to resolve maybe? + sigslots::MemberSlotsBase &member_slots = o; + sigslots::MemberSlot *slot = member_slots.addSlot(f,o); + if ( slot != NULL ) { + return sigslots::connect(signal,*slot); // koenig lookup also works + } else { + return sigslots::Error(sigslots::OutOfResourcesError); + } +} +/** + * @brief Convenience method to connect signal with global/static function. + * + * This simply passes on the work to Signal's connect method. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError : when the capacity of the global slots manager or the signal is exceeded. + * + * @param signal : the signal for connection. + * @param function : the global/static function to slot. + * @return Error : the sigslots error + */ +template +sigslots::Error connect(Signal &signal, void (*function)(Data), GlobalClass &g) { + sigslots::GlobalSlotsBase &global_slots = g; + sigslots::GlobalSlot *slot = global_slots.addSlot(function); + if ( slot != NULL ) { + return sigslots::connect(signal,*slot); + } else { + return sigslots::Error(sigslots::OutOfResourcesError); + } + +} + +/***************************************************************************** +** Publicly Used Connect Overloads +*****************************************************************************/ + +/** + * @brief Convenience method to connect signal with member function. + * + * This simply passes on the work to Signal's connect method. + * + * @param signal : the signal for connection. + * @param function : the member function to slot. + * @param o : the object associated with the member function. + * @return Error : the sigslots error + */ +template +sigslots::Error connect(Signal &signal, void(FunctionClass::*function)(void), FunctionClass &o) { + // Need to do this just in case o has member slot interfaces for multiple Data types. + // If we don't it can't resolve the footprint that seems to get lost when passing + // the function pointers down the line - another way to resolve maybe? + sigslots::MemberSlotsBase &member_slots = o; + sigslots::MemberSlot *slot = member_slots.addSlot(function,o); + if ( slot != NULL ) { + return sigslots::connect(signal,*slot); // koenig lookup also works + } else { + return sigslots::Error(sigslots::OutOfResourcesError); + } +} +/** + * @brief Convenience method to connect signal with global/static function. + * + * This simply passes on the work to Signal's connect method. + * + * @param signal : the signal for connection. + * @param function : the global/static function to slot. + * @return Error : the sigslots error + */ +template +sigslots::Error connect(Signal &signal, void (*function)(void), GlobalClass &g) { + sigslots::GlobalSlotsBase &global_slots = g; + sigslots::GlobalSlot *slot = global_slots.addSlot(function); + if ( slot != NULL ) { + return sigslots::connect(signal,*slot); + } else { + return sigslots::Error(sigslots::OutOfResourcesError); + } + +} + +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_CONNECT_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/errors.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/errors.hpp new file mode 100644 index 0000000..dfbf4ad --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/errors.hpp @@ -0,0 +1,78 @@ +/** + * @file /include/ecl/sigslots_lite/errors.hpp + * + * @brief Error handling types and classes for lite sigslots. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_ERRORS_HPP_ +#define ECL_SIGSLOTS_LITE_ERRORS_HPP_ + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { +namespace sigslots { + +/** + * @brief Error flags for lite sigslots. + * + * This is a subset of the ecl_errors class, reproduced here for + * semi-compatibility. Try and keep these matched with the ErrorFlag + * enums in ecl_errors for consistency. + */ +enum ErrorFlag { + NoError = 0, /**< No error (often a meaningful error state in itself). **/ + UnknownError = -1, /**< Unknown error type. **/ + OutOfResourcesError = -21, /**< Out of resources, cannot proceed. **/ +}; + +/** + * @brief Extends the generic ecl error handler with some time specific error strings. + * + * This error handler is used both by ecl_sigslots_lite + */ +class Error { +public: + /** + * @brief Configures the error class with the specified error flag. + * + * @param flag : the error type. + */ + Error(const sigslots::ErrorFlag& flag = UnknownError) : error_flag(flag) {} + /** + * @brief The flag identifying the error identified with this error handler. + * @return ErrorFlag : the error flag. + */ + virtual sigslots::ErrorFlag flag() const { return error_flag; } + /** + * @brief A simple string verbosely representing the error that is handled. + * + * @return const char* : verbose representation of the error. + */ + virtual const char* what() const { + switch (error_flag) { + case (NoError) : { return noErrorString(); } + case (OutOfResourcesError) : { return outOfResourcesErrorString(); } + default : { return unknownErrorString(); } + } + } +private: + const char* noErrorString() const { return "No error."; } + const char* unknownErrorString() const { return "Unknown error."; } + const char* outOfResourcesErrorString() const { return "You cannot add any more to this signal/slot interface (capacity is already fully utilised)."; } + ErrorFlag error_flag; + +}; + +} // namespace sigslots +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_ERRORS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/managers.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/managers.hpp new file mode 100644 index 0000000..bf30f2d --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/managers.hpp @@ -0,0 +1,403 @@ +/** + * @file /include/ecl/sigslots_lite/managers.hpp + * + * @brief Management classes for sigslots lite. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_MANAGERS_HPP_ +#define ECL_SIGSLOTS_LITE_MANAGERS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +#include "slot.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { + +/***************************************************************************** +** Forward Declarations +*****************************************************************************/ + +template class Signal; + +/***************************************************************************** +** Managers +*****************************************************************************/ + +namespace sigslots { +/** + * @brief Used internally to retrieve info about members lots. + */ +template +class MemberSlotsBase { +public: + virtual unsigned int stored() const { return 0; } + virtual unsigned int capacity() const { return 0; } + virtual sigslots::MemberSlot* addSlot(void (FunctionClass::*func)(Data), FunctionClass &instance) = 0; +}; + +/** + * @brief Used internally to retrieve info about void member slots. + */ +template +class MemberSlotsBase { +public: + virtual unsigned int stored() const { return 0; } + virtual unsigned int capacity() const { return 0; } + virtual sigslots::MemberSlot* addSlot(void (FunctionClass::*func)(), FunctionClass &instance) = 0; +}; + +template +class GlobalSlotsBase { +public: + virtual unsigned int stored() const { return 0; } + virtual unsigned int capacity() const { return 0; } + virtual sigslots::GlobalSlot* addSlot( void (*function)(Data) ) = 0; +}; + +template +class GlobalSlotsBase { +public: + virtual unsigned int stored() const { return 0; } + virtual unsigned int capacity() const { return 0; } + virtual sigslots::GlobalSlot* addSlot( void (*function)() ) = 0; +}; + +} // namespace sigslots + +/****************************************** +** Member Manager +*******************************************/ +/** + * @brief This is the member slot interface, inheritable by classes. + * + * To enable slots for your class, simply inherit this interface. + * + * @code + * class Foo : public ecl::lite::MemberSlots { + * public: + * void f(const char* str) { + * std::cout << "Foo::f() " << str << std::endl; + * } + * }; + * + * int main() { + * Foo foo; + * ecl::lite::Signal signal; + * connect(signal,&Foo::f,foo); + * signal.emit("Dude"); + * @endcode + * + * @tparam Data : the footprint for the member function to slot. + * @tparam FunctionClass : the class it will provide slots for. + * @tparam Capacity : the number of functions from FunctionClass you'll slot. + */ +template +class MemberSlots : public sigslots::MemberSlotsBase { +public: + /********************* + ** Friends + **********************/ + // allow connect to use addSlot + template + friend sigslots::Error connect(Signal &signal, void(FunctionClass_::*f)(Data_), FunctionClass_ &o); + + // needs access to stored() + template + friend unsigned int member_slots_stored(const FunctionClass_ &object); + + // needs access to capacity() + template + friend unsigned int member_slots_capacity(const FunctionClass_ &object); + + +protected: + MemberSlots() : size(0) {}; + +private: + /** + * @brief The number of slots stored. + * + * @return unsigned int : storage size. + */ + unsigned int stored() const { return size; } + /** + * @brief The number of slots that can be attached to member functions. + * + * @return unsigned int : the maximum capacity. + */ + unsigned int capacity() const { return Capacity; } + + /** + * @brief Add a slot. + * + * This is used 'under the hood' by the connectors. + * + * @param func : the function to slot. + * @param instance : the class instance associated with the function. + * @return MemberSlot* : a pointer to a member slot. + */ + sigslots::MemberSlot* addSlot(void (FunctionClass::*func)(Data), FunctionClass &instance) { + for ( unsigned int i = 0; i < size; ++i ) { + if ( func == slots[i].member_function ) { + return &(slots[i]); + } + } + if ( size < Capacity ) { + slots[size] = sigslots::MemberSlot(func,instance); + ++size; + return &(slots[size-1]); + } else { + return NULL; + } + } + + unsigned int size; + sigslots::MemberSlot slots[Capacity]; +}; + +/****************************************** +** Global Manager +*******************************************/ + +template +class GlobalSlots : public sigslots::GlobalSlotsBase { +public: + /********************* + ** Friends + **********************/ + // allow connect to use addSlot + template + friend sigslots::Error connect(Signal &signal, void(*function)(Data_), GlobalClass_ &g); + + // needs access to stored() + template + friend unsigned int global_slots_stored(); + + // needs access to capacity() + template + friend unsigned int global_slots_capacity(); + +protected: + GlobalSlots() : size(0) {}; + +private: + /** + * @brief The number of slots stored. + * + * @return unsigned int : storage size. + */ + unsigned int stored() const { return size; } + /** + * @brief The number of slots that can be attached to member functions. + * + * @return unsigned int : the maximum capacity. + */ + unsigned int capacity() const { return Capacity; } + + /** + * @brief Add a slot. + * + * This is used 'under the hood' by the connectors. + * + * @param func : the function to slot. + * @param instance : the class instance associated with the function. + * @return MemberSlot* : a pointer to a member slot. + */ + sigslots::GlobalSlot* addSlot(void (*function)(Data)) { + for ( unsigned int i = 0; i < size; ++i ) { + if ( function == slots[i].global_function ) { + return &(slots[i]); + } + } + if ( size < Capacity ) { + slots[size] = sigslots::GlobalSlot(function); + ++size; + return &(slots[size-1]); + } else { + return NULL; + } + } + + unsigned int size; + sigslots::GlobalSlot slots[Capacity]; +}; + +/***************************************************************************** +** Specialisations +*****************************************************************************/ +/** + * @brief Specialisation for void member slots management. + */ +template +class MemberSlots : public sigslots::MemberSlotsBase { +public: + /********************* + ** Friends + **********************/ + // allow connect to use addSlot + template + friend sigslots::Error connect(Signal &signal, void(FunctionClass_::*f)(void), FunctionClass_ &o); + // needs access to stored() + template + friend unsigned int member_slots_stored(const FunctionClass_ &object); + + // needs access to capacity() + template + friend unsigned int member_slots_capacity(const FunctionClass_ &object); + +protected: + MemberSlots() : size(0) {}; + +private: + /** + * @brief The number of slots stored. + * + * @return unsigned int : storage size. + */ + unsigned int stored() const { return size; } + + /** + * @brief The number of slots that can be attached to member functions. + * + * @return unsigned int : the maximum capacity. + */ + unsigned int capacity() const { return Capacity; } + + /** + * @brief Add a slot. + * + * This is used 'under the hood' by the connectors. + * + * @param func : the function to slot. + * @param instance : the class instance associated with the function. + * @return MemberSlot* : a pointer to a member slot. + */ + sigslots::MemberSlot* addSlot(void (FunctionClass::*func)(void), FunctionClass &instance) { + for ( unsigned int i = 0; i < size; ++i ) { + if ( func == slots[i].member_function ) { + return &(slots[i]); + } + } + if ( size < Capacity ) { + slots[size] = sigslots::MemberSlot(func,instance); + ++size; + return &(slots[size-1]); + } else { + return NULL; + } + } + + unsigned int size; + sigslots::MemberSlot slots[Capacity]; +}; + +template +class GlobalSlots : public sigslots::GlobalSlotsBase { +public: + /********************* + ** Friends + **********************/ + // allow connect to use addSlot + template + friend sigslots::Error connect(Signal &signal, void(*function)(void), GlobalClass_ &g); + + // needs access to stored() + template + friend unsigned int global_slots_stored(); + + // needs access to capacity() + template + friend unsigned int global_slots_capacity(); + +protected: + GlobalSlots() : size(0) {}; + +private: + /** + * @brief The number of slots stored. + * + * @return unsigned int : storage size. + */ + unsigned int stored() const { return size; } + /** + * @brief The number of slots that can be attached to member functions. + * + * @return unsigned int : the maximum capacity. + */ + unsigned int capacity() const { return Capacity; } + + /** + * @brief Add a slot. + * + * This is used 'under the hood' by the connectors. + * + * @param func : the function to slot. + * @param instance : the class instance associated with the function. + * @return GlobalSlot* : a pointer to a member slot. + */ + sigslots::GlobalSlot* addSlot(void (*function)()) { + for ( unsigned int i = 0; i < size; ++i ) { + if ( function == slots[i].global_function ) { + return &(slots[i]); + } + } + if ( size < Capacity ) { + slots[size] = sigslots::GlobalSlot(function); + ++size; + return &(slots[size-1]); + } else { + return NULL; + } + } + + unsigned int size; + sigslots::GlobalSlot slots[Capacity]; +}; + + +class Joe { +public: + static inline void addSlot() { + // static std::array::capacity> dods; + static std::array dods; + dods[0] = 3.0; + // std::cout << "Capacity: " << GlobalSlots::capacity << std::endl; + std::cout << dods[0] << std::endl; + } +}; + + +//template +//struct GlobalManager : public GlobalSlots {}; + +// template +// const GlobalManager& global_manager() { +// static GlobalManager god{}; +// return god; +// } + +//template <> +//const GlobalManager& global_manager() { +// static GlobalManager god{}; +// return god; +//} + + +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_MANAGERS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/signal.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/signal.hpp new file mode 100644 index 0000000..ebb3b6c --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/signal.hpp @@ -0,0 +1,226 @@ +/** + * @file /ecl_sigslots_lite/include/ecl/sigslots_lite/signal.hpp + * + * @brief Simple signal interface. + * + * Could probably set up a signal base for these, but its ok as is. + * + * @date Feb, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_SIGNAL_HPP_ +#define ECL_SIGSLOTS_LITE_SIGNAL_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "slot.hpp" +#include "errors.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { + +/***************************************************************************** +** Classes +*****************************************************************************/ +/** + * @brief A simple signal class. + * + * This class, once instantiated and connected is a fixed entity. + * Memory reserved for slots is fixed and disconnects are not + * possible This allows us to avoid the use of new and in most + * low level control programs, such disconnects are rarely used + * anyway. + * + * To reserve the capacity (i.e. no. of slots that can be attached) + * configure the second template parameter upon instantiation. Note + * that the default is 1. + * + * @code + * void f(int i) { + * std::cout << i << std::endl; + * } + * int main() { + * + * Signal signal; // Signal provides a default of 1 + * connect(signal,f) + * signal.emit(3); + * // ... + * @endcode + * + * @tparam Data : the data type to emit. + * @tparam Capacity : the number of slot connections to reserve. + */ +template +class Signal { +public: + /** + * @brief Initialise the storage. + */ + Signal() { + for ( unsigned int i = 0; i < Capacity; ++i) { + slots[i] = NULL; + } + } + /** + * @brief Connect the signal to the specified slot. + * + * This will attach the slot (note that it is a + * permanent attachment) so long as the reserved + * capacity isn't already fully utilised. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError + * + * @param slot : the slot to connect. + * @return Error : the sigslots error + */ + sigslots::Error connect(sigslots::SlotBase &slot) { + for (unsigned int i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + slots[i] = &slot; + return sigslots::Error(sigslots::NoError); + } + } + // if we reach here, we've run out of resources. + return sigslots::Error(sigslots::OutOfResourcesError); + } + /** + * @brief The reserved capacity for this signaller. + * + * @return unsigned int : the capacity. + */ + unsigned int capacity() const { return Capacity; } + /** + * @brief The current number of connections stored. + * + * @return unsigned int : no. of connections. + */ + unsigned int stored() const { + unsigned int i; + for (i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + break; + } + } + return i; + + } + + /** + * @brief Signal slots with the specified data. + * + * @param data : the data to send to the slots. + */ + void emit(Data data) const { + for (unsigned int i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + break; + } else { + slots[i]->execute(data); + } + } + } + +private: + sigslots::SlotBase *slots[Capacity]; +}; + +/** + * @brief Specialisation of the signal for data-less sigslots. + * + * Specialises the signal class for use with void callbacks. In + * this situation, it is purely a signaller, nothing else. + * + * @tparam Capacity : the number of slot connections to reserve. + */ +template +class Signal { +public: + /** + * @brief Initialise the storage. + */ + Signal() { + for ( unsigned int i = 0; i < Capacity; ++i) { + slots[i] = NULL; + } + } + /** + * @brief Connect the signal to the specified slot. + * + * This will attach the slot (note that it is a + * permanent attachment) so long as the reserved + * capacity isn't already fully utilised. + * + * Valid return values: + * + * - NoError + * - OutOfResourcesError + * + * @param slot : the slot to connect. + * @return Error : the sigslots error + */ + sigslots::Error connect(sigslots::SlotBase &slot) { + for (unsigned int i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + slots[i] = &slot; + return sigslots::Error(sigslots::NoError); + } + } + // if we reach here, we've run out of resources. + return sigslots::Error(sigslots::OutOfResourcesError); + } + /** + * @brief The reserved capacity for this signaller. + * + * @return unsigned int : the capacity. + */ + unsigned int capacity() const { return Capacity; } + + /** + * @brief The current number of connections stored. + * + * @return unsigned int : no. of connections. + */ + unsigned int stored() const { + unsigned int i; + for (i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + break; + } + } + return i; + + } + /** + * @brief Signal slots with the specified data. + */ + void emit() const { + for (unsigned int i = 0; i < Capacity; ++i ) { + if ( slots[i] == NULL ) { + break; + } else { + slots[i]->execute(); + } + } + } + +private: + sigslots::SlotBase *slots[Capacity]; +}; + + +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_SIGNAL_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/slot.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/slot.hpp new file mode 100644 index 0000000..2336a5d --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/slot.hpp @@ -0,0 +1,149 @@ +/** + * @file /ecl_sigslots_lite/include/ecl/sigslots_lite/slot.hpp + * + * @brief Simple slots - these are actually all hidden from the user. + * + * @date Feb, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_SLOT_HPP_ +#define ECL_SIGSLOTS_LITE_SLOT_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // defines NULL + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { + +/***************************************************************************** +** Slots +*****************************************************************************/ + +namespace sigslots { +/** + * @brief Parent slot class with the common, publicly exposed interface. + * + * This allows member and global slots to be used as one and the same. + * + * @tparam Data : the function callback arg type (footprint). + */ +template +class SlotBase { +public: + virtual void execute(Data data) = 0; +}; +/** + * @brief A slot with member callback function. + * + * @tparam Data : the argument type. + * @tparam FunctionClass : the type of the class the function belongs too. + */ +template +class MemberSlot : public SlotBase { +public: + MemberSlot() {} + MemberSlot(void (FunctionClass::*func)(Data), FunctionClass &instance) : + object(&instance), + member_function(func) + {} + + void execute(Data data) { + (*object.*member_function)(data); + } + FunctionClass *object; + void (FunctionClass::*member_function)(Data); +private: +}; + + +/** + * @brief A slot with global/static callback function. + * + * @tparam Data : the argument type. + */ +template +class GlobalSlot : public SlotBase { +public: + GlobalSlot() : global_function(NULL) {} + GlobalSlot(void (*func)(Data)) : global_function(func) {} + + void execute(Data data) { + if ( global_function != NULL ) { + (*global_function)(data); + } + } + void (*global_function)(Data); /**< @brief Slotted function. **/ +}; + +/***************************************************************************** +** Slot Specialisations +*****************************************************************************/ + +/** + * @brief Parent slot class with the common, publicly exposed interface. + * + * This allows member and global void slots to be used as one and the same. + */ +template <> +class SlotBase { +public: + virtual void execute() = 0; +}; + +/** + * @brief A slot with member callback function. + * + * @tparam Data : the argument type. + * @tparam FunctionClass : the type of the class the function belongs too. + */ +template +class MemberSlot : public SlotBase { +public: + MemberSlot() {} + MemberSlot(void (FunctionClass::*func)(void), FunctionClass &instance) : + object(&instance), + member_function(func) + {} + + void execute() { + (*object.*member_function)(); + } + FunctionClass *object; + void (FunctionClass::*member_function)(void); +private: +}; + +/** + * @brief A slot with global/static callback function. + * + * @tparam Data : the argument type. + */ +template <> +class GlobalSlot : public SlotBase { +public: + GlobalSlot() : global_function(NULL) {} + GlobalSlot(void (*func)(void)) : global_function(func) {} + + void execute() { + if ( global_function != NULL ) { + (*global_function)(); + } + } + void (*global_function)(void); /**< @brief Slotted function. **/ +}; + +} // namespace sigslots +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_SLOT_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/utilities.hpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/utilities.hpp new file mode 100644 index 0000000..e32f722 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/include/ecl/sigslots_lite/utilities.hpp @@ -0,0 +1,55 @@ +/** + * @file /ecl_sigslots_lite/include/ecl/sigslots_lite/utilities.hpp + * + * @brief Utility functions + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_SIGSLOTS_LITE_UTILITY_HPP_ +#define ECL_SIGSLOTS_LITE_UTILITY_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "managers.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +namespace lite { + +template +unsigned int global_slots_stored(const GlobalClass &object) { + const sigslots::GlobalSlotsBase &global_slots = object; + return global_slots.stored(); +} + +template +unsigned int global_slots_capacity(const GlobalClass &object) { + const sigslots::GlobalSlotsBase &global_slots = object; + return global_slots.capacity(); +} + +template +unsigned int member_slots_stored(const FunctionClass &object) { + const sigslots::MemberSlotsBase &member_slots = object; + return member_slots.stored(); +} + +template +unsigned int member_slots_capacity(const FunctionClass &object) { + const sigslots::MemberSlotsBase &member_slots = object; + return member_slots.capacity(); +} + +} // namespace lite +} // namespace ecl + +#endif /* ECL_SIGSLOTS_LITE_UTILITY_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/mainpage.dox new file mode 100644 index 0000000..e1ea4df --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/mainpage.dox @@ -0,0 +1,155 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This is a light version of ecl_sigslots and provides a + very ruthlessly simple signals and slots mechanisms useful for + *very* embedded development. You can read more about + signals and slots in the ecl_sigslots package. + + +\section Differences + + Some differences between from ecl_sigslots + + - Not thread safe... + + This is a bit of a vague statement on its own. In essence, its usually + important to make sure your signals and slots finish processing any + currently executing slots before they self destruct. Most sigslot + implementations dont do this, ecl_sigslots does, but ecl_sigslots_lite + does not. If you have a monolothic program with a single thread, this + probably doesn't matter, but if not, then you must take care to ensure + signals and slots close appropriately. On the plus side, there is no + dependency on platform api for mutexes. + + - No disconnects... + + Adding disconnect capability adds alot of complexity to the sigslots + implementation. Lite sigslots assume that signals and slots connections, + once fixed until the signal goes out of scope. + + - No dynamic storage (no heap storage with malloc/new)... + + This is often verboten with various embedded compilers and introduces + alot of system overhead. Lite sigslots allocates memory up front and + will not permit overuse thereafter. + + - Self contained... + + While utilising things like standard error flag constructors (from ecl_errors) + might be convenient, this package is and likely will often be used + standalone in a firmware project. As a result, its designed with its own + internal mechanisms (e.g. error class). This implies that a simple 'make + sources' (refer to ecl_build's documentation for more information) + is sufficient to gather header and source files for direct inclusion into + a firmware project. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // Signals + using ecl::lite::Signal; + + // Functions + using ecl::lite::connect + using ecl::lite::global_slots_stored; + using ecl::lite::global_slots_capacity; + using ecl::lite::member_slots_stored; + using ecl::lite::member_slots_capacity; + @endcode + + As its a template header library, you do not need to link. + +\section usage Usage + + \subsection Slots + + Users of lite sigslots don't actually directly use Slot classes (unlike ecl_sigslots). + Slots are still there, but they are stored behind the scenes, either in a global slots + manager or member slots manager inherited by a class. + + \subsection Storage Storage Capacities + + Signals and slots need to reserve memory before usage. For global slots, you need to + set a static variable before making any connections to slots of that type. + + @code + // allocate for global function slots with const char* and void arg footprints + class GlobalManager : public ecl::lite::GlobalSlots, + public ecl::lite::GlobalSlots + { + public: + GlobalManager() {}; + }; + int main() { + GlobalManager global_manager; + // ... + @endcode + + For member slots, your class needs to inherit from the MemberSlots interface and + specify the capacity as a template parameter (default is 1). + + @code + class Foo : public ecl::lite::MemberSlots, + public ecl::lite::MemberSlots + { + public: + Foo() {} + + void f(const char* str) { /* */ } + void g() { /* */ } + void h() { /* */ } + }; + @endcode + + For signals, simply specify the capacity template parameter (again default is 1) + when instantiating the signal. This reflects the number of connections it can + handle. + + @code + ecl::lite::Signal signal; + @endcode + + @subsection Connections + + Connections are made via the connect functions, linking directly to the function + pointers. + + @code + connect(signal,f, global_manager); // connecting to a global slot + connect(signal,&Foo::f, foo); // connecting to a member slot + @endcode + + @subsection Utilities + + There are some utility functions for debugging. + + @code + // statistics for global slots with arg type 'const char*' + std::cout << ecl::lite::global_slots_stored(global_manager) << std::endl; + std::cout << ecl::lite::global_slots_capacity(global_manager) << std::endl; + + // statistics for global slots with no args + std::cout << ecl::lite::global_slots_stored(global_manager) << std::endl; + std::cout << ecl::lite::global_slots_capacity(global_manager) << std::endl; + + // statistics for member slots of foo with no args + std::cout << ecl::lite::member_slots_stored(foo) << std::endl; + std::cout << ecl::lite::member_slots_capacity(foo) << std::endl; + @endcode + + +\section Examples + + These are more of a rough coverage test. + + - src/examples/sigslots.cpp +*/ diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/package.xml b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/package.xml new file mode 100644 index 0000000..c5fdbc8 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/package.xml @@ -0,0 +1,31 @@ + + + ecl_sigslots_lite + 1.2.0 + + This avoids use of dynamic storage (malloc/new) and thread safety (mutexes) to + provide a very simple sigslots implementation that can be used for *very* + embedded development. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_sigslots_lite + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_license + ecl_config + ecl_errors + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/CMakeLists.txt new file mode 100644 index 0000000..f812ed9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Subdirectories +############################################################################## + +#add_subdirectory(lib) +add_subdirectory(examples) +#add_subdirectory(test) \ No newline at end of file diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/CMakeLists.txt new file mode 100644 index 0000000..bdc5b52 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +add_executable(demo_sigslots_lite sigslots.cpp) +target_link_libraries(demo_sigslots_lite ${PROJECT_NAME}) +install(TARGETS demo_sigslots_lite RUNTIME DESTINATION lib/${PROJECT_NAME}) diff --git a/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/sigslots.cpp b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/sigslots.cpp new file mode 100644 index 0000000..5cadc7c --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_sigslots_lite/src/examples/sigslots.cpp @@ -0,0 +1,176 @@ +/** + * @file /ecl_sigslots_lite/src/examples/sigslots.cpp + * + * @brief File comment + * + * File comment + * + * @date 17/02/2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "../../include/ecl/sigslots_lite.hpp" + +/***************************************************************************** +** Foo +*****************************************************************************/ +/** + * @cond NoDoxygen + */ +class Foo : public ecl::lite::MemberSlots, + public ecl::lite::MemberSlots +{ +public: + Foo() {} + + void f(const char* str) { + std::cout << "Foo::f() " << str << std::endl; + } + void h() { + std::cout << "Foo::h()" << std::endl; + } +}; + +class GlobalManager : public ecl::lite::GlobalSlots, + public ecl::lite::GlobalSlots +{ +public: + GlobalManager() {}; +}; + +void f(const char* str) { + std::cout << "f(char*) " << str << std::endl; +} + +void g(const char* str) { + std::cout << "g(char*) " << str << std::endl; +} + +void h() { + std::cout << "h()" << std::endl; +} + +/** + * @endcond NoDoxygen + */ + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main(int /*argc*/, char** /*argv*/) { + + Foo foo; + GlobalManager global_manager; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Data Sigslots" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::lite::Signal dual_slot_signal; + ecl::lite::Signal lone_signal1, lone_signal2; + ecl::lite::connect(dual_slot_signal, f, global_manager); + ecl::lite::connect(dual_slot_signal, g, global_manager); + std::cout << std::endl; + dual_slot_signal.emit("one signal, two global slots"); + + ecl::lite::connect(lone_signal1,&Foo::f,foo); + lone_signal1.emit("direct member slot connection"); + std::cout << std::endl; + + ecl::lite::connect(lone_signal2,&Foo::f,foo); + lone_signal1.emit("multiple signals, one slot connection - I"); + lone_signal2.emit("multiple signals, one slot connection - II"); + std::cout << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Void Sigslots" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::lite::Signal void_signal, member_void_signal; + connect(member_void_signal,&Foo::h, foo); + connect(void_signal, h, global_manager); + void_signal.emit(); + member_void_signal.emit(); + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Storage" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "GlobalSlots Stored : " << ecl::lite::global_slots_stored(global_manager) << std::endl; + std::cout << "GlobalSlots Capacity: " << ecl::lite::global_slots_capacity(global_manager) << std::endl; + std::cout << std::endl; + std::cout << "GlobalSlots Stored : " << ecl::lite::global_slots_stored(global_manager) << std::endl; + std::cout << "GlobalSlots Capacity: " << ecl::lite::global_slots_capacity(global_manager) << std::endl; + std::cout << std::endl; + + std::cout << "MemberSlots Stored(foo) : " << ecl::lite::member_slots_stored(foo) << std::endl; + std::cout << "MemberSlots Capacity(Foo): " << ecl::lite::member_slots_capacity(foo) << std::endl; + std::cout << std::endl; + std::cout << "MemberSlots Stored(foo) : " << ecl::lite::member_slots_stored(foo) << std::endl; + std::cout << "MemberSlots Capacity(Foo): " << ecl::lite::member_slots_capacity(foo) << std::endl; + std::cout << std::endl; + + ecl::lite::Signal signal_storage_test; + std::cout << "Incrementally adding slots to signal" << std::endl; + std::cout << " capacity: " << signal_storage_test.capacity() << std::endl; + std::cout << " stored : " << signal_storage_test.stored() << std::endl; + connect(signal_storage_test,f, global_manager); + std::cout << " stored : " << signal_storage_test.stored() << std::endl; + connect(signal_storage_test,g, global_manager); + std::cout << " stored : " << signal_storage_test.stored() << std::endl; + std::cout << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Error Handling" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + ecl::lite::sigslots::Error error; + std::cout << "Adding two slots to a single slot capacity signal." << std::endl; + ecl::lite::Signal one_shot_signal; + std::cout << " Connecting a first slot" << std::endl; + error = connect(one_shot_signal,f, global_manager); + if ( error.flag() != ecl::lite::sigslots::NoError ) { + std::cout << " " << error.what() << std::endl; + } + std::cout << " Connecting a second slot" << std::endl; + error = connect(one_shot_signal,f, global_manager); + if ( error.flag() != ecl::lite::sigslots::NoError ) { + std::cout << " " << error.what() << std::endl; + } + std::cout << std::endl; + + std::cout << "Adding two slots to a single slot capacity MemberSlots interface." << std::endl; + ecl::lite::Signal two_shot_signal; + Foo foo_new; // 0 slots stored in MemberSlots + std::cout << " Connecting a first slot" << std::endl; + error = connect(two_shot_signal, &Foo::f, foo_new); // 1 slot stored in MemberSlots + if ( error.flag() != ecl::lite::sigslots::NoError ) { + std::cout << " " << error.what() << std::endl; + } + std::cout << " Connecting a second slot" << std::endl; + error = connect(two_shot_signal, &Foo::f, foo_new); // 2nd slot, when only 1 declared, fail! + if ( error.flag() != ecl::lite::sigslots::NoError ) { + std::cout << " " << error.what() << std::endl; + } + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +} diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/.cproject b/ros2_ws/src/ecl_lite/ecl_time_lite/.cproject new file mode 100644 index 0000000..792d562 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/.cproject @@ -0,0 +1,672 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + all + + true + + true + + true + + + + + + make + + clean + + true + + true + + true + + + + + + make + + + + examples + + true + + true + + true + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/.project b/ros2_ws/src/ecl_lite/ecl_time_lite/.project new file mode 100644 index 0000000..4df3dc9 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/.project @@ -0,0 +1,79 @@ + + + ecl_time_lite + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/.settings/language.settings.xml b/ros2_ws/src/ecl_lite/ecl_time_lite/.settings/language.settings.xml new file mode 100644 index 0000000..f56a843 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/.settings/language.settings.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/CHANGELOG.rst b/ros2_ws/src/ecl_lite/ecl_time_lite/CHANGELOG.rst new file mode 100644 index 0000000..73feac2 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/CHANGELOG.rst @@ -0,0 +1,21 @@ +========= +Changelog +========= + +1.0.3 (2018-08-21) +------------------ +* pedantic error message fixes for const error string methods on clang/macosx + +0.61.1 (2015-07-26) +------------------- +* support get_date_string on macosx. + +0.61.0 (2014-09-12) +------------------- +* unique get date string function for unique filename creation. +* optional flag for getting real time instead of monolithic posix time (this syncs with ROS) + +0.60.1 (2014-01-29) +------------------- +* update to catkin's CFG_EXTRAS for easy to find cmake modules. +* Contributors: Daniel Stonier diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/CMakeLists.txt new file mode 100644 index 0000000..93edb4f --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/CMakeLists.txt @@ -0,0 +1,56 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(ecl_time_lite) + +############################################################################## +# Find Packages +############################################################################## + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +find_package(ament_cmake_ros REQUIRED) +find_package(ecl_build REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_errors REQUIRED) + +############################################################################## +# Project Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include) + +# This configures ECL_PLATFORM_TIME_LIBRARIES and +# other ECL_PLATFORM_HAS_XXX flags +ecl_detect_timers() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +# Downstream CMake3 compatibility +ament_export_targets(HAS_LIBRARY_TARGET ${PROJECT_NAME}) +# Downstream CMake2 compatibility +ament_export_include_directories(include) +ament_export_libraries(${PROJECT_NAME}) + +ament_export_dependencies( + ecl_config + ecl_errors +) +ament_package() diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/include/CMakeLists.txt new file mode 100644 index 0000000..0275c2e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/CMakeLists.txt @@ -0,0 +1,5 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/CMakeLists.txt new file mode 100644 index 0000000..3fda63a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/CMakeLists.txt @@ -0,0 +1,13 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(time_lite) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite.hpp new file mode 100644 index 0000000..00b564c --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite.hpp @@ -0,0 +1,27 @@ +/** + * @file /include/ecl/time_lite.hpp + * + * @brief Collects headers for ecl_time_lite. + * + * @date February 2011. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_HPP_ +#define ECL_TIME_LITE_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "time_lite/macros.hpp" +#include "time_lite/errors.hpp" +#include "time_lite/types.hpp" +#include "time_lite/date.hpp" +#include "time_lite/functions.hpp" +#include "time_lite/cpu_time.hpp" + +#endif /* ECL_TIME_LITE_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/.gitignore b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/.gitignore new file mode 100644 index 0000000..a8361bc --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/.gitignore @@ -0,0 +1 @@ +config.hpp diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/CMakeLists.txt new file mode 100644 index 0000000..d126eba --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/CMakeLists.txt @@ -0,0 +1,50 @@ +############################################################################### +# Generate Header +############################################################################### +############################################################################## +# Initialisation +############################################################################## + + +############################################################################## +# Symbol Generation (for ecl/time_lite/config.hpp +############################################################################## + +# see ecl_detect_posix and ecl_detect_timers in +# ecl_build/cmake/modules/ecl_platform_detection.cmake + +if(ECL_POSIX_HAS_CLOCK_GETTIME) + set(ECL_PRIVATE_HAS_CLOCK_GETTIME 1) +endif() +if(ECL_POSIX_HAS_CLOCK_NANOSLEEP) + set(ECL_PRIVATE_HAS_CLOCK_NANOSLEEP 1) +endif() +if(ECL_POSIX_HAS_CLOCK_MONOTONIC) + set(ECL_HAS_CLOCK_MONOTONIC 1) +endif() +if(ECL_POSIX_HAS_CPUTIME) + set(ECL_HAS_CPUTIME 1) +endif() +if(ECL_PLATFORM_HAS_MACH_TIMERS) + set(ECL_HAS_MACH_TIMERS 1) +endif() +if(ECL_PLATFORM_HAS_WIN_TIMERS) + set(ECL_HAS_WIN_TIMERS 1) +endif() +if(ECL_PLATFORM_HAS_RT_TIMERS) + set(ECL_HAS_RT_TIMERS 1) +endif() +if(ECL_PLATFORM_HAS_POSIX_TIMERS) + set(ECL_HAS_POSIX_TIMERS 1) +endif() + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/config.hpp) + +############################################################################## +# Files +############################################################################## + +file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp) + +install(FILES ${HEADERS} DESTINATION include/ecl/time_lite) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/config.hpp DESTINATION include/ecl/time_lite) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/config.hpp.in b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/config.hpp.in new file mode 100644 index 0000000..92b5e76 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/config.hpp.in @@ -0,0 +1,116 @@ +/** + * @file /include/ecl/time_lite/config.hpp + * + * @brief Pre-processed macros that define time for the platform. + * + * Cmake is used to check/verify your target platform parameters related + * to time functions. At the moment this is all automated. If ever this + * needs to change (i.e. if we need to hand configure some macros as per + * ecl_config style) then we should move this to ecl_config itself. + * + * @date February 2011 + **/ +/***************************************************************************** +** Guards +*****************************************************************************/ + +#ifndef ECL_TIME_CONFIG_HPP_ +#define ECL_TIME_CONFIG_HPP_ + +/***************************************************************************** +** Include +*****************************************************************************/ + +#include + +/** + * @addtogroup Macros + * @{ +**/ + +/***************************************************************************** +** Private macros +*****************************************************************************/ +/** + * @def ECL_PRIVATE_HAS_CLOCK_GETTIME + * + * @brief The platform has clock_gettime() from -lrt. +**/ +#cmakedefine ECL_PRIVATE_HAS_CLOCK_GETTIME +/** + * @def ECL_PRIVATE_HAS_CLOCK_NANOSLEEP + * + * @brief The platform has clock_nanosleep() from -lrt. +**/ +#cmakedefine ECL_PRIVATE_HAS_CLOCK_NANOSLEEP + +/***************************************************************************** +** Public macros +*****************************************************************************/ +/** + * @def ECL_HAS_CLOCK_MONOTONIC + * + * @brief Can utilise monotonic clocks. + * + * These come with -lrt and allow use of timers which are guaranteed not + * to jump. +**/ +#cmakedefine ECL_HAS_CLOCK_MONOTONIC +/** + * @def ECL_HAS_CPUTIME + * + * @brief Can set clocks measuring time spent on the cpu (-lrt). +**/ +#cmakedefine ECL_HAS_CPUTIME + +/** + * @def ECL_HAS_MACH_TIMERS + * + * @brief Ecl uses the mac timers. + * + * - ECL_HAS_WIN_TIMERS + * - ECL_HAS_RT_TIMERS + * - ECL_HAS_POSIX_TIMERS +**/ +#cmakedefine ECL_HAS_MACH_TIMERS +/** + * @def ECL_HAS_WIN_TIMERS + * + * @brief Ecl uses the win timers. + * + * - ECL_HAS_RT_TIMERS + * - ECL_HAS_MACH_TIMERS + * - ECL_HAS_POSIX_TIMERS +**/ +#cmakedefine ECL_HAS_WIN_TIMERS + +/** + * @def ECL_HAS_RT_TIMERS + * + * @brief Ecl uses the real time (-lrt) timers. + * + * This assumption was made by checking for the presence of clock_gettime, + * and clock_nanosleep. See also: + * + * - ECL_HAS_WIN_TIMERS + * - ECL_HAS_MACH_TIMERS + * - ECL_HAS_POSIX_TIMERS +**/ +#cmakedefine ECL_HAS_RT_TIMERS + +/** + * @def ECL_HAS_POSIX_TIMERS + * + * @brief Ecl uses the default posix timers. + * + * - ECL_HAS_WIN_TIMERS + * - ECL_HAS_MACH_TIMERS + * - ECL_HAS_RT_TIMERS +**/ +#cmakedefine ECL_HAS_POSIX_TIMERS +/** + * @} + **/ + +#endif /* ECL_TIME_CONFIG_HPP_ */ + \ No newline at end of file diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/cpu_time.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/cpu_time.hpp new file mode 100644 index 0000000..824072f --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/cpu_time.hpp @@ -0,0 +1,52 @@ +/** + * @file /ecl_time_lite/include/ecl/time_lite/cpu_time.hpp + * + * @brief Timer for measuring time spent sitting on the cpu. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_CPU_TIME_HPP_ +#define ECL_TIME_LITE_CPU_TIME_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "errors.hpp" +#include "types.hpp" +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +#ifdef ECL_HAS_CPUTIME +/** + * @brief Cpu time function provided by librt. + * + * This provides the time spent by the process executing on the cpu. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - ArgNotSupported, + * - PermissionsError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError cpu_time(TimeStructure &time); +#endif + +} // namespace ecl + +#endif /* ECL_TIME_LITE_CPU_TIME_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/date.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/date.hpp new file mode 100644 index 0000000..ad91168 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/date.hpp @@ -0,0 +1,50 @@ +/** + * @file /include/ecl/time_lite/date.hpp + * + * @brief Date manipulations. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_DATE_HPP_ +#define ECL_TIME_LITE_DATE_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include + +#if defined(ECL_HAS_POSIX_TIMERS) || defined (ECL_HAS_RT_TIMERS) || defined(ECL_HAS_MACH_TIMERS) || defined(ECL_HAS_WIN_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementations +*****************************************************************************/ + +/** + * @brief Get the date/time as a string. + * + * Simple function to generate a usable string for uniquely creating + * things like filenames. + */ +ecl_time_lite_PUBLIC std::string get_date_string(); + +} // namespace ecl + +#endif // POSIX or RT TIMERS + +#endif // ECL_TIME_LITE_DATE_HPP_ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/errors.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/errors.hpp new file mode 100644 index 0000000..9c866bf --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/errors.hpp @@ -0,0 +1,53 @@ +/** + * @file /ecl_time_lite/include/ecl/time_lite/errors.hpp + * + * @brief File comment + * + * File comment + * + * @date Feb 16, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_ERRORS_HPP_ +#define ECL_TIME_LITE_ERRORS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Extends the ecl error handler with time specific error strings. + */ +class ecl_time_lite_PUBLIC TimeError : public Error { +public: + /** + * @brief Configures the error class with the specified error flag. + * + * @param flag : the error type. + */ + TimeError(const ErrorFlag& flag = UnknownError) : Error(flag) {} + +protected: + virtual const char* outOfRangeErrorString() const { return "The input time sec/nsec pair was outside of the permitted range."; } + virtual const char* argNotSupportedErrorString() const { return "The clock specified is not supported on this system."; } + virtual const char* permissionsErrorString() const { return "You do not have permission to set the specified clock."; } + virtual const char* memoryErrorString() const { return "One of the input arguments is not in memory addressable space."; } + virtual const char* interruptedErrorString() const { return "This operation was interrupted by a signal."; } +}; + +} // namespace ecl + +#endif /* ECL_TIME_LITE_ERRORS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions.hpp new file mode 100644 index 0000000..a12382f --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions.hpp @@ -0,0 +1,49 @@ +/** + * @file /include/ecl/time_lite/functions.hpp + * + * @brief Platform specific incantations of the time functions. + * + * Platform specific incantations of the time functions. These + * are notoriously different depending on the platform - linux has librt, + * mac osx the mach functions and windoze ???. + * + * These are only for use internally by the ecl time classes - a user should + * never need to know them. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_FUNCTIONS_HPP_ +#define ECL_TIME_LITE_FUNCTIONS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#if defined(ECL_HAS_MACH_TIMERS) + #include "functions_mac.hpp" +#elif defined(ECL_HAS_RT_TIMERS) + // monotonic clock -> clock_gettime; clock_selection -> clock_nanosleep + // #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK) >= 0L && defined(_POSIX_CLOCK_SELECTION) && (_POSIX_CLOCK_SELECTION) >= 0L + #include "functions_rt.hpp" +#elif defined(ECL_HAS_POSIX_TIMERS) + #include "functions_pos.hpp" +#elif defined(ECL_HAS_WIN_TIMERS) + // basic system time functions (horrid resolution and little functionality!) + #include "functions_win.hpp" +#else + #error("There is not a supporting time implementation on this platform (possibly needs extended ecl support).") +#endif + +#endif /* ECL_TIME_LITE_FUNCTIONS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_mac.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_mac.hpp new file mode 100644 index 0000000..9afdc60 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_mac.hpp @@ -0,0 +1,100 @@ +/** + * @file /include/ecl/time_lite/functions_mac.hpp + * + * @brief Mach implementation of ecl time functions. + * + * This is to make up for the fact that macosx does not have librt. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_FUNCTIONS_MAC_HPP_ +#define ECL_TIME_LITE_FUNCTIONS_MAC_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_HAS_MACH_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include // gettimeofday +#include +#include "errors.hpp" +#include "types.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Using +*****************************************************************************/ + +/** + * @brief Mach implementation of gettime on a macosx. + * + * This is better than the fallback posix implementation, but still doesn't + * quite implement monotonic time. Mac has a better timer function, but + * I've not investigated it yet. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError epoch_time(TimeStructure &time); + + +/** + * @brief Fallback approximation to an absolute timed sleep. + * + * If librt is unavailable we have to use this approximation to its + * absolutely timed nanosleep function. If used in a control loop, + * there will be some drift. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : the absolute time to sleep until. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep_until(const TimeStructure &time); + +/** + * @brief A regular sleep function that operates relative to 'now'. + * + * This has high resolution, but its accuracy will depend on your + * scheduler. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : the period to sleep for. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep(const TimeStructure &time); + +} // namespace ecl + +#endif +#endif /* ECL_TIME_LITE_FUNCTIONS_MAC_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_pos.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_pos.hpp new file mode 100644 index 0000000..a8cc225 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_pos.hpp @@ -0,0 +1,106 @@ +/** + * @file /include/ecl/time_lite/functions_pos.hpp + * + * @brief Simple posix implementation of ecl time functions. + * + * This implementation has its problems - most notably that you cannot get + * monotonic functionality. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_FUNCTIONS_POS_HPP_ +#define ECL_TIME_LITE_FUNCTIONS_POS_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_HAS_POSIX_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include // time structs, nanosleep +#include // gettimeofday +#include +#include "errors.hpp" +#include "types_pos.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Implementations +*****************************************************************************/ +/** + * @brief Posix fallback function for gettime when better functions unavailable. + * + * This is a simple implementation of the gettime and is used within the ecl + * as a fallback for posix systems which don't have better timers. The main + * drawback with this one is it is not monotonic and can suffer from wrap + * around problems. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - ArgNotSupported, + * - PermissionsError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError epoch_time(TimeStructure &time); + +/** + * @brief Fallback approximation to an absolute timed sleep. + * + * If librt is unavailable we have to use this approximation to its + * absolutely timed nanosleep function. If used in a control loop, + * there will be some drift. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - OutOfRangeError, + * - InterruptedError. + * + * @param time : the time to sleep until. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep_until(const TimeStructure &time); + +/** + * @brief A regular sleep function that operates relative to 'now'. + * + * This has high resolution, but its accuracy will depend on your + * scheduler. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - OutOfRangeError, + * - InterruptedError. + * + * @param time : the period to sleep for. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep(const TimeStructure &time); + +} // namespace ecl + +#endif +#endif /* ECL_TIME_LITE_FUNCTIONS_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_rt.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_rt.hpp new file mode 100644 index 0000000..8ebb603 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_rt.hpp @@ -0,0 +1,115 @@ +/** + * @file /include/ecl/time_lite/functions_rt.hpp + * + * @brief Real-time implementation of ecl time functions. + * + * Real-time (librt) implementation of ecl time functions. + * + * @date March 2010 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_FUNCTIONS_RT_HPP_ +#define ECL_TIME_LITE_FUNCTIONS_RT_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_HAS_RT_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "errors.hpp" +#include "types.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { +/** + * @brief Monotonic gettime function provided by librt. + * + * This is the best case scenario - it's high resolution and its monotonic. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - ArgNotSupported, + * - PermissionsError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError epoch_time(TimeStructure &time); + +/** + * @brief Realtime gettime function provided by librt. + * + * For those rare cases when you absolutely have to fallback to realtime + * instead of using the monotone clock. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - ArgNotSupported, + * - PermissionsError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError realtime_epoch_time(TimeStructure &time); + +/** + * @brief Monotonic absolute timed sleep function provided by librt. + * + * This is the best implementation of a sleeper which does not + * cause drift in a periodic control loop. It tunes in on absolute + * times rather than relative times. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - OutOfRangeError, + * - InterruptedError. + * + * @param time : the absolute time to sleep until. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep_until(const TimeStructure &time); + +/** + * @brief A regular sleep function that operates relative to 'now'. + * + * This has high resolution, but its accuracy will depend on your + * scheduler. + * + * Valid return values: + * + * - NoError, + * - MemoryError, + * - OutOfRangeError, + * - InterruptedError. + * + * @param time : the period to sleep for. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep(const TimeStructure &time); + +} // namespace ecl + +#endif +#endif /* ECL_TIME_LITE_FUNCTIONS_RT_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_win.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_win.hpp new file mode 100644 index 0000000..26d8dc0 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/functions_win.hpp @@ -0,0 +1,99 @@ +/** + * @file /include/ecl/time_lite/functions_win.hpp + * + * @brief Windows interfaces for ecl time functions. + * + * @date February 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_FUNCTIONS_WIN_HPP_ +#define ECL_TIME_LITE_FUNCTIONS_WIN_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_HAS_WIN_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "types_win.hpp" +#include "errors.hpp" +#include "macros.hpp" + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Functions +*****************************************************************************/ + +/** + * @brief Gets the time in seconds/nanoseconds from some landmark point. + * + * This is not actually epoch time, but its good enough. It pulls the + * amount of time since the computer has actually been turned on. To get the epoch + * time you'll need a bit more machinery - you can find an example in ros's + * rostime/src/time.cpp. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : time structure. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError epoch_time(TimeStructure &time); + +/** + * @brief Fallback to an approximation of an absolute sleep function. + * + * This imitates rt's absolute sleeper which will sleep exactly + * until the specified time. This one instead will just generate + * some time differences which will, if used in a control loop, + * generate some drift. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : the absolute time to sleep until. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep_until(const TimeStructure &time); + +/** + * @brief A regular sleep function that operates relative to 'now'. + * + * This is the windows implementation and it doesn't have a great + * deal of resolution. + * + * Valid return values: + * + * - NoError, + * - UnknownError. + * + * @param time : the period to sleep for. + * @return TimeError : error result. + */ +ecl_time_lite_PUBLIC TimeError sleep(const TimeStructure &time); + +} // namespace ecl + +#endif +#endif /* ECL_TIME_LITE_FUNCTIONS_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/macros.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/macros.hpp new file mode 100644 index 0000000..1caec02 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/macros.hpp @@ -0,0 +1,42 @@ +/** + * @file /include/ecl/time_lite/macros.hpp + * + * @brief Macros for error-checking and program termination. + * + * Macros for error-checking and program termination. + * + * @date April 2013. + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_MACROS_HPP_ +#define ECL_TIME_LITE_MACROS_HPP_ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include + +/***************************************************************************** +** PreProcessing +*****************************************************************************/ +/* + * Import/exports symbols for the library + */ +#ifdef ECL_HAS_SHARED_LIBS // ecl is being built around shared libraries + #ifdef ecl_time_lite_EXPORTS // we are building a shared lib/dll + #define ecl_time_lite_PUBLIC ECL_HELPER_EXPORT + #else // we are using shared lib/dll + #define ecl_time_lite_PUBLIC ECL_HELPER_IMPORT + #endif + #define ecl_time_lite_LOCAL ECL_HELPERS_LOCAL +#else // ecl is being built around static libraries + #define ecl_time_lite_PUBLIC + #define ecl_time_lite_LOCAL +#endif + + +#endif /* ECL_TIME_LITE_MACROS_HPP_*/ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types.hpp new file mode 100644 index 0000000..205a2a8 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types.hpp @@ -0,0 +1,33 @@ +/** + * @file /include/ecl/time_lite/types.hpp + * + * @brief Cross platform definition for time types. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_TYPES_HPP_ +#define ECL_TIME_LITE_TYPES_HPP_ + +/***************************************************************************** +** Cross Platform Functionality +*****************************************************************************/ + +#include + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#if defined(ECL_HAS_WIN_TIMERS) + #include "types_win.hpp" +#elif defined(ECL_HAS_MACH_TIMERS) || defined(ECL_HAS_POSIX_TIMERS) || defined(ECL_HAS_RT_TIMERS) // should probably get cmake to check for timespec. + #include "types_pos.hpp" +#else + #error("There is not a supporting time implementation on this platform (possibly needs extended ecl support).") +#endif + +#endif /* ECL_TIME_LITE_TYPES_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_pos.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_pos.hpp new file mode 100644 index 0000000..efc774f --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_pos.hpp @@ -0,0 +1,46 @@ +/** + * @file /include/ecl/time_lite/types_pos.hpp + * + * @brief Posix definition for time types. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_TYPES_POS_HPP_ +#define ECL_TIME_LITE_TYPES_POS_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include + +#if defined(ECL_HAS_MACH_TIMERS) || defined(ECL_HAS_POSIX_TIMERS) || defined(ECL_HAS_RT_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/** + * @brief Standard cross platform time structure. + * + * This is already supplied by posix systems as timespec. + */ +typedef timespec TimeStructure; + +} // namespace ecl + +#endif +#endif /* ECL_TIME_LITE_TYPES_POS_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_win.hpp b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_win.hpp new file mode 100644 index 0000000..0dc22ed --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/include/ecl/time_lite/types_win.hpp @@ -0,0 +1,53 @@ +/** + * @file /include/ecl/time_lite/types_win.hpp + * + * @brief Cross platform definition for time types. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Ifdefs +*****************************************************************************/ + +#ifndef ECL_TIME_LITE_TYPES_WIN_HPP_ +#define ECL_TIME_LITE_TYPES_WIN_HPP_ + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include +#include "macros.hpp" + +#if defined(ECL_HAS_WIN_TIMERS) + +/***************************************************************************** +** Include +*****************************************************************************/ + +#include +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Structures +*****************************************************************************/ + +/** + * @brief Standard cross platform time structure. + * + * Simply replicates the posix timespec structure. + */ +struct ecl_time_lite_PUBLIC TimeStructure { + time_t tv_sec; + long tv_nsec; +}; + +} // namespace ecl +#endif +#endif /* ECL_TIME_LITE_TYPES_WIN_HPP_ */ diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/mainpage.dox b/ros2_ws/src/ecl_lite/ecl_time_lite/mainpage.dox new file mode 100644 index 0000000..dc96df6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/mainpage.dox @@ -0,0 +1,70 @@ +/** +\mainpage +\htmlinclude manifest.html + +\section packageSummary Package Summary + + This provides a portable set of time functions that are especially useful for porting + other code or being wrapped by higher level c++ classes. + + Code has been divided broadly via a set of cmake probes into the following groups: + + - ECL_HAS_WIN_TIMERS + - ECL_HAS_MACH_TIMERS - apple operating systems. + - ECL_HAS_RT_TIMERS + - ECL_HAS_POSIX_TIMERS - the fallback posix functions when -lrt is not available. + +@section CompilingLinking Compiling & Linking + + Include the following at the top of any translation unit which + requires this library: + + @code + #include + + // The portable time functions. + using ecl::time_lite::sleep; + using ecl::time_lite::sleep_until; + using ecl::time_lite::epoch_time; + + // Platform specific function (-lrt). + using ecl::time_lite::cpu_time; + @endcode + + You will also need to link to -lecl_time_lite. + +\section usage Usage + + Use with the TimeError (an extension of ecl_errors' Error handler) that provides time function specific verbose error messages. + + @code + ecl::TimeStructure duration; + duration.tv_sec = 1; + duration.tv_nsec = 300000000; + ecl::TimeError error = ecl::sleep(duration); + if ( error.flag() != ecl::NoError) { + std::cout << error.what() << std::endl; + // do something + } + @endcode + + The function epoch_time is often not exactly epoch time (i.e. secs from 1970), but dependant on your + platform. Nonetheless, it always provides a relative timer measuring in sec/nsecs. Note that the + time is only guaranteed to be monotonic (i.e. it won't jump) if cmake has defined + ECL_HAS_CLOCK_MONOTONIC. + + The function cpu_time which is the amount of time that the process has actually + spent executing on the cpu. This one is sometimes useful for benchmarking tests. + +\section unitTests Unit Tests + + These don't really suit gtests, so a simple coverage example, ctest style, is provided. + + - src/examples/time_functions.cpp + +\section ChangeLog + + - Feb 11 : moved the portable api across from ecl_time and wrapped in the new error handlers. + + +*/ \ No newline at end of file diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/package.xml b/ros2_ws/src/ecl_lite/ecl_time_lite/package.xml new file mode 100644 index 0000000..364a39a --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/package.xml @@ -0,0 +1,31 @@ + + + ecl_time_lite + 1.2.0 + + Provides a portable set of time functions that are especially useful for + porting other code or being wrapped by higher level c++ classes. + + Daniel Stonier --> + Daniel Stonier + BSD + http://wiki.ros.org/ecl_time_lite + https://github.com/stonier/ecl_lite + https://github.com/stonier/ecl_lite/issues + + ament_cmake_ros + + ecl_license + ecl_build + ecl_config + ecl_errors + ecl_license + ecl_build + ecl_config + ecl_errors + + ament_cmake + + + + diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/src/CMakeLists.txt new file mode 100644 index 0000000..a9c0ba6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/CMakeLists.txt @@ -0,0 +1,6 @@ +############################################################################## +# Subdirectories +############################################################################## + +add_subdirectory(lib) +add_subdirectory(examples) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/CMakeLists.txt new file mode 100644 index 0000000..6d1bd72 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/CMakeLists.txt @@ -0,0 +1,7 @@ +############################################################################## +# Files +############################################################################## + +add_executable(demo_time_functions time_functions.cpp) +target_link_libraries(demo_time_functions ${PROJECT_NAME}) +install(TARGETS demo_time_functions RUNTIME DESTINATION lib/${PROJECT_NAME}) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/time_functions.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/time_functions.cpp new file mode 100644 index 0000000..5d4895e --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/examples/time_functions.cpp @@ -0,0 +1,116 @@ +/** + * @file /ecl_time_lite/src/examples/time_functions.cpp + * + * @brief Ctest style coverage test for the ecl_time_lite functions. + * + * Not really feasible converting this into a gtest. + * + * @date February, 2011 + **/ + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include +#include +#include "../../include/ecl/time_lite/date.hpp" +#include "../../include/ecl/time_lite/functions.hpp" +#include "../../include/ecl/time_lite/cpu_time.hpp" + + +/***************************************************************************** +** Main +*****************************************************************************/ + +int main() { + +#if defined(ECL_HAS_POSIX_TIMERS) || defined(ECL_HAS_RT_TIMERS) || defined(ECL_HAS_WIN_TIMERS) || defined(ECL_HAS_MACH_TIMERS) + ecl::TimeError error; + ecl::TimeStructure duration, timestamp; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Sleep" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + + std::cout << "Sleep: Duration 1.3s" << std::endl; + duration.tv_sec = 1; + duration.tv_nsec = 300000000; + error = ecl::sleep(duration); + if ( error.flag() != ecl::NoError ) { + abort(); + } + + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Epoch Time" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + error = ecl::epoch_time(timestamp); + if ( error.flag() != ecl::NoError ) { + abort(); + } + std::cout << "Epoch Time:" << std::endl; + std::cout << " sec : " << timestamp.tv_sec << std::endl; + std::cout << " nsec: " << timestamp.tv_nsec << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Sleep Until" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + timestamp.tv_sec += 2; + std::cout << "Sleeping until current_time + 2 seconds." << std::endl; + error = ecl::sleep_until(timestamp); + if ( error.flag() != ecl::NoError ) { + abort(); + } + +#ifdef ECL_HAS_CPUTIME + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Cpu Time" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + error = ecl::cpu_time(timestamp); + if ( error.flag() != ecl::NoError ) { + abort(); + } + std::cout << "Cpu Time:" << std::endl; + std::cout << " sec : " << timestamp.tv_sec << std::endl; + std::cout << " nsec: " << timestamp.tv_nsec << std::endl; +#endif + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Date String" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + std::cout << "Date String: " << ecl::get_date_string() << std::endl; + + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " Passed" << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; + + return 0; +#else + std::cout << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << " This platform does not support timers. " << std::endl; + std::cout << "***********************************************************" << std::endl; + std::cout << std::endl; +#endif + +} diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/CMakeLists.txt b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/CMakeLists.txt new file mode 100644 index 0000000..dfd74e6 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/CMakeLists.txt @@ -0,0 +1,35 @@ +############################################################################## +# Files +############################################################################## + +file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp) + +############################################################################### +# Targets +############################################################################### + +add_library(${PROJECT_NAME} ${SOURCES}) +target_include_directories( + ${PROJECT_NAME} + PUBLIC + $ + $ + $ +) +target_link_libraries(${PROJECT_NAME} + PUBLIC + ecl_config::ecl_config + ecl_errors::ecl_errors + ${ECL_PLATFORM_TIME_LIBRARIES} +) +set_target_properties(${PROJECT_NAME} + PROPERTIES + SOVERSION ${${PROJECT_NAME}_VERSION} + VERSION ${${PROJECT_NAME}_VERSION} +) + +install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib +) diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/cpu_time.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/cpu_time.cpp new file mode 100644 index 0000000..65ad401 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/cpu_time.cpp @@ -0,0 +1,38 @@ +/** + * @file /ecl_time_lite/src/lib/cpu_time.cpp + * + * @brief Implemntation of the cpu timer. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time_lite/cpu_time.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +#ifdef ECL_HAS_CPUTIME +TimeError cpu_time(TimeStructure &time) { + // On the man page, it says that this function should need _POSIX_CPUTIME + // defined, but in practice I'm a bit unusre about this. On one system, + // I've had _POSIX_CPUTIME defined to 0, but this function would still work. + // Just assuming that you need clock_gettime for now. + int result = clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&time); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINVAL) : { return TimeError(ArgNotSupportedError); } // clock id is not supported (actually impossible if cmake detects) + case(EPERM) : { return TimeError(PermissionsError); } // user does not have permissions to use the clock. + default : { return TimeError(UnknownError); } + } +} +#endif + +} // namespace ecl diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/date.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/date.cpp new file mode 100644 index 0000000..8955cd1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/date.cpp @@ -0,0 +1,47 @@ +/** + * @file /src/lib/date.cpp + * + * @brief Implementation of date manipulators. + **/ + + +/***************************************************************************** +** Cross Platform Configuration +*****************************************************************************/ + +#include + +#if defined(ECL_HAS_POSIX_TIMERS) || defined(ECL_HAS_RT_TIMERS) || defined(ECL_HAS_MACH_TIMERS) || defined(ECL_HAS_WIN_TIMERS) + +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time_lite/date.hpp" +#include + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + + +std::string get_date_string() { + time_t now; + char the_date[12]; + + the_date[0] = '\0'; + now = time(NULL); + if (now != -1) + { + // this makes use of the variable LC_TIME + // it also gives me incorrect time on my machine, wrong time zone? + strftime(the_date, 17, "%Y%m%d-%H%M%S", gmtime(&now)); + } + return std::string(the_date); +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_mac.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_mac.cpp new file mode 100644 index 0000000..786b7d1 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_mac.cpp @@ -0,0 +1,87 @@ +/** + * @file /src/lib/functions_mac.cpp + * + * @brief Mac implementation of ecl time functions. + * + * @date January 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time_lite/functions_mac.hpp" +#include + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#if defined(ECL_HAS_MACH_TIMERS) + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +TimeError epoch_time(TimeStructure &time) { + struct timeval tv; + int result = gettimeofday(&tv, NULL); + if ( result == 0 ) { + time.tv_sec = tv.tv_sec; + time.tv_nsec = tv.tv_usec*1000; + return TimeError(NoError); + } else { + switch (errno) { + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINVAL) : { return TimeError(ArgNotSupportedError); } // timezone (or something else) is invalid + default : { return TimeError(UnknownError); } + } + } +} + +TimeError sleep_until(const TimeStructure &time) { + TimeStructure current_time, sleep_time; + + TimeError error = epoch_time(current_time); + if ( error.flag() != NoError ) { return error; } + + /********************* + ** current > time? + **********************/ + if ( current_time.tv_sec > time.tv_sec ) { + return TimeError(NoError); // return immediately + } else if ( current_time.tv_sec == time.tv_sec ) { + if ( current_time.tv_nsec > time.tv_nsec ) { + return TimeError(NoError); // return immediately + } + } + sleep_time.tv_sec = time.tv_sec - current_time.tv_sec; + if ( current_time.tv_nsec <= time.tv_nsec ) { + sleep_time.tv_nsec = time.tv_nsec - current_time.tv_nsec; + } else { + sleep_time.tv_sec -= 1; + sleep_time.tv_nsec = 1000000000L - current_time.tv_nsec + time.tv_nsec; + } + int result = nanosleep(&sleep_time, NULL); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // some memory error copying information around + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} + +TimeError sleep(const TimeStructure &time) { + int result = nanosleep(&time, NULL); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // some memory error copying information around + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} +} // namespace ecl +#endif diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_pos.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_pos.cpp new file mode 100644 index 0000000..4f3b2f3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_pos.cpp @@ -0,0 +1,89 @@ +/** + * @file /src/lib/functions_pos.cpp + * + * @brief Posix implementation of ecl time functions. + * + * Posix implementation of ecl time functions. + * + * @date January 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time_lite/functions_pos.hpp" +#include + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#if defined(ECL_HAS_POSIX_TIMERS) + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +TimeError epoch_time(TimeStructure &time) { + struct timeval tv; + int result = gettimeofday(&tv, NULL); + if ( result == 0 ) { + time.tv_sec = tv.tv_sec; + time.tv_nsec = tv.tv_usec*1000; + return TimeError(NoError); + } else { + switch (errno) { + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINVAL) : { return TimeError(ArgNotSupportedError); } // timezone (or something else) is invalid + default : { return TimeError(UnknownError); } + } + } +} +TimeError sleep_until(const TimeStructure &time) { + TimeStructure current_time, sleep_time; + + TimeError error = epoch_time(current_time); + if ( error.flag() != NoError ) { return error; } + + /********************* + ** current > time? + **********************/ + if ( current_time.tv_sec > time.tv_sec ) { + return TimeError(NoError); // return immediately + } else if ( current_time.tv_sec == time.tv_sec ) { + if ( current_time.tv_nsec > time.tv_nsec ) { + return TimeError(NoError); // return immediately + } + } + sleep_time.tv_sec = time.tv_sec - current_time.tv_sec; + if ( current_time.tv_nsec <= time.tv_nsec ) { + sleep_time.tv_nsec = time.tv_nsec - current_time.tv_nsec; + } else { + sleep_time.tv_sec -= 1; + sleep_time.tv_nsec = 1000000000L - current_time.tv_nsec + time.tv_nsec; + } + int result = nanosleep(&sleep_time, NULL); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // some memory error copying information around + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} +TimeError sleep(const TimeStructure &time) { + int result = nanosleep(&time, NULL); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // some memory error copying information around + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_rt.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_rt.cpp new file mode 100644 index 0000000..b8c72d3 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_rt.cpp @@ -0,0 +1,84 @@ +/** + * @file /src/lib/functions_rt.cpp + * + * @brief Real-time (librt) implementation of ecl time functions. + * + * @date January 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include "../../include/ecl/time_lite/functions_rt.hpp" +#include + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#if defined(ECL_HAS_RT_TIMERS) + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +TimeError epoch_time(TimeStructure &time) { + // _POSIX_CLOCK_MONOTONIC should have gotten us this far, + // just check if we have CLOCK_MONOTONIC and if not, fallback to + // CLOCK_REALTIME. +#ifdef ECL_HAS_CLOCK_MONOTONIC + int result = clock_gettime(CLOCK_MONOTONIC,&time); +#else + int result = clock_gettime(CLOCK_REALTIME,&time); +#endif + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINVAL) : { return TimeError(ArgNotSupportedError); } // clock id is not supported (actually impossible if cmake detects) + case(EPERM) : { return TimeError(PermissionsError); } // user does not have permissions to use the clock. + default : { return TimeError(UnknownError); } + } +} + +TimeError realtime_epoch_time(TimeStructure &time) { + int result = clock_gettime(CLOCK_REALTIME,&time); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINVAL) : { return TimeError(ArgNotSupportedError); } // clock id is not supported (actually impossible if cmake detects) + case(EPERM) : { return TimeError(PermissionsError); } // user does not have permissions to use the clock. + default : { return TimeError(UnknownError); } + } +} + +TimeError sleep_until(const TimeStructure &time) { + // Last arg is to catch remaining time if interrupted by a signal, not necessary here. +#ifdef ECL_HAS_CLOCK_MONOTONIC + int result = clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&time,NULL); +#else + int result = clock_nanosleep(CLOCK_REALTIME,TIMER_ABSTIME,&time,NULL); +#endif + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // time was not in addressable memory space + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} +TimeError sleep(const TimeStructure &time) { + int result = nanosleep(&time, NULL); + switch (result) { + case(0) : { return TimeError(NoError); } + case(EFAULT) : { return TimeError(MemoryError); } // some memory error copying information around + case(EINTR) : { return TimeError(InterruptedError); } // interrupted by a signal + case(EINVAL) : { return TimeError(OutOfRangeError); } // sec/nsec pair specified was out of range + default : { return TimeError(UnknownError); } + } +} + +} // namespace ecl + +#endif diff --git a/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_win.cpp b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_win.cpp new file mode 100644 index 0000000..1c8d048 --- /dev/null +++ b/ros2_ws/src/ecl_lite/ecl_time_lite/src/lib/functions_win.cpp @@ -0,0 +1,123 @@ +/** + * @file /src/lib/functions_win.cpp + * + * @brief Windows implementation of ecl time functions. + * + * @date February, 2011 + **/ +/***************************************************************************** +** Includes +*****************************************************************************/ + +#include +#include +#include "../../include/ecl/time_lite/functions_win.hpp" + +/***************************************************************************** +** Macros +*****************************************************************************/ + +#if defined(ECL_HAS_WIN_TIMERS) + +/***************************************************************************** +** Namespaces +*****************************************************************************/ + +namespace ecl { + +/***************************************************************************** +** Notes +*****************************************************************************/ + +// This is defined by windows and looks like this: +//typedef union _LARGE_INTEGER { +// struct { +// DWORD LowPart; +// LONG HighPart; +// }; +// LONGLONG QuadPart; +//} LARGE_INTEGER; +//typedef LARGE_INTEGER TimeStructure; /**< @brief The underlying type used to store time structures. **/ + +/***************************************************************************** +** Private functions +*****************************************************************************/ + +static double cpu_frequency() { + static double frequency = 0.0; + + if ( frequency == 0.0 ) { // need to initialise + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + frequency = static_cast(freq.QuadPart); + } + return frequency; +} + +/***************************************************************************** +** Public functions +*****************************************************************************/ + +TimeError epoch_time(TimeStructure &time) { + // Get time + LARGE_INTEGER stamp; + QueryPerformanceCounter(&stamp); + double t = static_cast(stamp.QuadPart)/cpu_frequency(); + time.tv_sec = static_cast(t); + time.tv_nsec = ((t - static_cast(time.tv_sec))*1000000000.0); + return TimeError(NoError); +} + +TimeError sleep_until(const TimeStructure &time) { + TimeStructure current_time, sleep_time; + + TimeError error = epoch_time(current_time); + if ( error.flag() != NoError ) { return error; } + + /********************* + ** current > time? + **********************/ + if ( current_time.tv_sec > time.tv_sec ) { + return TimeError(NoError); // return immediately + } else if ( current_time.tv_sec == time.tv_sec ) { + if ( current_time.tv_nsec > time.tv_nsec ) { + return TimeError(NoError); + } + } + sleep_time.tv_sec = time.tv_sec - current_time.tv_sec; + if ( current_time.tv_nsec <= time.tv_nsec ) { + sleep_time.tv_nsec = time.tv_nsec - current_time.tv_nsec; + } else { + sleep_time.tv_sec -= 1; + sleep_time.tv_nsec = 1000000000L - current_time.tv_nsec + time.tv_nsec; + } + return ecl::sleep(sleep_time); +} + +TimeError sleep(const TimeStructure &time) { + HANDLE timer = NULL; + LARGE_INTEGER sleep_time; + + sleep_time.QuadPart = static_cast(time.tv_nsec) / 100LL - + static_cast(time.tv_sec) * 10000000LL; +// sleep_time.QuadPart = - +// static_cast(time.tv_sec)*10000000LL - +// static_cast(time.tv_nsec) / 100LL; + + if ( (timer = CreateWaitableTimer(NULL, TRUE, NULL)) == NULL ) { + return TimeError(UnknownError); + } + if (!SetWaitableTimer (timer, &sleep_time, 0, NULL, NULL, 0)) { + return TimeError(UnknownError); + } + + if (WaitForSingleObject (timer, INFINITE) != WAIT_OBJECT_0) { + return TimeError(UnknownError); + } + return TimeError(NoError); +} + + +} // namespace ecl + +#endif // POSIX_TIMERS || RT_TIMERS || WIN_TIMERS diff --git a/ros2_ws/src/kobuki_core b/ros2_ws/src/kobuki_core deleted file mode 160000 index 3e0652d..0000000 --- a/ros2_ws/src/kobuki_core +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3e0652dc4006d8345a86298ac05d82049747bc7f diff --git a/ros2_ws/src/kobuki_core/.cproject b/ros2_ws/src/kobuki_core/.cproject new file mode 100644 index 0000000..a11de74 --- /dev/null +++ b/ros2_ws/src/kobuki_core/.cproject @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + -j8 + + all + + true + + true + + true + + + + + + make + + -j8 + + clean + + true + + true + + true + + + + + + make + + -j8 + + install + + true + + true + + true + + + + + + + + + + diff --git a/ros2_ws/src/kobuki_core/.github/workflows/devel.yaml b/ros2_ws/src/kobuki_core/.github/workflows/devel.yaml new file mode 100644 index 0000000..8f9c44e --- /dev/null +++ b/ros2_ws/src/kobuki_core/.github/workflows/devel.yaml @@ -0,0 +1,40 @@ + +name: doxygen-build-commit-push + +on: + push: + branches: [ devel ] + +jobs: + build: + # The type of runner that the job will run on + runs-on: ubuntu-20.04 + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + - uses: mattnotmitt/doxygen-action@v1 + with: + working-directory: "doc/" + doxyfile-path: "./doxy.conf" + + - name: commit changes + run: | + git clone https://github.com/kobuki-base/kobuki_core.git --branch gh-pages --single-branch gh-pages + cp -r doc/generated/html/* gh-pages/ + touch gh-pages/.nojekyll + cd gh-pages + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add . + # this command will fail if there we no changes, ignore the return code + git commit -m "[action] documentation update" -a || true + + - name: push changes + uses: ad-m/github-push-action@master + with: + branch: gh-pages + directory: gh-pages + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/ros2_ws/src/kobuki_core/.github/workflows/pull_requests.yaml b/ros2_ws/src/kobuki_core/.github/workflows/pull_requests.yaml new file mode 100644 index 0000000..8d83b3c --- /dev/null +++ b/ros2_ws/src/kobuki_core/.github/workflows/pull_requests.yaml @@ -0,0 +1,22 @@ + +name: doxygen-build-only + +on: + workflow_dispatch: + pull_request: + branches: [ devel ] + +jobs: + build: + # The type of runner that the job will run on + runs-on: ubuntu-20.04 + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + - uses: mattnotmitt/doxygen-action@v1 + with: + working-directory: "doc/" + doxyfile-path: "./doxy.conf" diff --git a/ros2_ws/src/kobuki_core/.gitignore b/ros2_ws/src/kobuki_core/.gitignore new file mode 100644 index 0000000..91c57d7 --- /dev/null +++ b/ros2_ws/src/kobuki_core/.gitignore @@ -0,0 +1,7 @@ +/doc/generated +.settings +build/ +bin/ +lib/ +*.swp +*.pyc diff --git a/ros2_ws/src/kobuki_core/.project b/ros2_ws/src/kobuki_core/.project new file mode 100644 index 0000000..5383a51 --- /dev/null +++ b/ros2_ws/src/kobuki_core/.project @@ -0,0 +1,27 @@ + + + kobuki_core + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/ros2_ws/src/kobuki_core/60-kobuki.rules b/ros2_ws/src/kobuki_core/60-kobuki.rules new file mode 100644 index 0000000..7c3768c --- /dev/null +++ b/ros2_ws/src/kobuki_core/60-kobuki.rules @@ -0,0 +1,6 @@ +# On precise, for some reason, USER and GROUP are getting ignored. +# So setting mode = 0666 for now. +SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", ATTRS{serial}=="kobuki*", ATTR{device/latency_timer}="1", MODE:="0666", GROUP:="dialout", SYMLINK+="kobuki" +# Bluetooth module (currently not supported and may have problems) +# SUBSYSTEM=="tty", ATTRS{address}=="00:00:00:41:48:22", MODE:="0666", GROUP:="dialout", SYMLINK+="kobuki" + diff --git a/ros2_ws/src/kobuki_core/CHANGELOG.rst b/ros2_ws/src/kobuki_core/CHANGELOG.rst new file mode 100644 index 0000000..7be8cbc --- /dev/null +++ b/ros2_ws/src/kobuki_core/CHANGELOG.rst @@ -0,0 +1,157 @@ +========= +Changelog +========= + +Forthcoming +----------- +* ... + +1.4.0 (2022-10-24) +------------------ +* [demos] log levels demo added, `#42 `_ +* [driver] bugfix major, minor, patch macro conflicts, `#44 `_ +* [demos] style cleanups, `#47 `_ +* [driver] grammar fixes, `#47 `_ + +1.3.1 (2020-09-15) +------------------ +* [keyop] protect command variables with a mutex, `#41 `_ +* [core] ros_ prefixes dropped, custom_logging & raw_data_stream demos, `#40 `_ +* [infra] recommended firmware versions 1.1.4, 1.2.0, `#37 `_ + +1.3.0 (2020-09-12) +------------------ +* [all] LegacyPose2D -> Vector3d, `#36 `_ + +1.2.0 (2020-08-30) +------------------ +* [infra] kobuki_dock_drive and kobuki_driver merged into kobuki_core, `#31 `_ +* [tools] kobuki_simple_keyop -> kobuki-simple-keyop, `#35 `_. +* [tools] kobuki_version_info -> kobuki-version-info, `#35 `_. + +1.1.1 (2020-08-19) +------------------ +* [udev] bugfix low latency ftdi operation, `#28 `_. +* [demos] added an event demo, also minor cleanup, `#27 `_. +* [infra] don't use system headers for dependencies, `#27 `_. + +1.1.0 (2020-08-04) +------------------ +* [infra] ament_export_interfaces -> ament_export_targets, `#21 `_. +* [driver] bugfix correct size for pyaload length lookup, #19 `_. +* [infra] license links updated, `#15 `_. + +1.0.0 (2020-01-13) +------------------ +* [infra] port and release for ROS2/Eloquent +* [infra] udev rule and debian installation thereof, `#13 `_. + +0.8.1 (2019-01-09) +------------------ +* remove unused and dodgy float builder, fixed uninitialised warnings, `#53 `_. + +0.8.0 (2019-01-09) +------------------ +* updated build infra for changes ament/eloquent + +0.7.7 (2017-03-29) +------------------ +* accel limiter variable initialisation bugfix + +0.7.6 (2017-03-27) +------------------ +* doxygen updates + +0.7.4 (2017-02-23) +------------------ +* drop spurious debugging cmake message that was throwing warnings + +0.7.2 (2016-11-09) +------------------ +* Pose2D -> LegacyPose2D + +0.7.1 (2016-05-06) +------------------ +* isnan -> std::isnan + +0.6.3 (2016-05-06) +------------------ +* bugfix cliff header packet + +0.6.2 (2016-01-09) +------------------ +* enable the cx11 compiler + +0.6.0 (2014-08-04) +------------------ +* add linear and angular test plot image +* kobuki_core : Updated doxygen. Issue `#10 `_. +* Contributors: Younghun Ju, jihoonl + +0.5.3 (2013-09-06) +------------------ +* Updated doxygen documentation. + +0.5.2 (2013-08-31) +------------------ +* Documentation and other text files reviewed. + +0.5.1 (2013-08-30) +------------------ +* Updated license info. +* Updated doxygen in the code. +* Update firmware_changelog.md. + +0.5.0 (2013-08-29) +------------------ +* Added debug topic of raw control command of robot. +* Removed debugging message. +* Updated doxygen about factory-default value of PID gain. +* Add firmware version checking on PID commands. +* Updated protocol specification in doxygen about custom PID gain setting. +* Updated doxygen script to let user do something when authentification of repository is failed. +* Bump minor version for firmware (new version is 1.2.0). +* Improved packet integrity checking. Issue `#245 `_. +* Added new protocol about custom PID gain setting. Issue `#249 `_. +* Updated doxygen. +* Removed ros logging code. +* Removed meaningless buffer size check in serialization of command packet. +* Fixed typo; mayor --> major. +* Added integrity check for each packets. +* Removed old printf codes. +* Removed meaningless buffer size check in serialization of packets. +* Fixed typo on update_doxygen.bash script. +* Added extra url info on all packages. +* Added brief description of update_doxygen.bash script. +* Added convenient script for automated update of doxygen document to the github.io page. +* Updated doxygen. +* Updated old rnd email address. +* Removed SetPower command packet from doxygen. It is not for external powers and unnecessary for kobuki. +* Corrected typos on doxygen about external power. +* lock api for protecting data access with asynchronous getXXX calls. +* Fix URL to the previous changelog wiki +* Changelogs at package level +* Reset odometry also for heading +* Updated raw_control_command topic to publish recevied command velocity also. +* Added a debug topic that publish actual base command sent to robot. +* Added simple_keyop application to control kobuki directly from keyboard without ROS. +* Fixed broken synchronity of base control command caused by recent bugfix of acceleration limiter module. +* Added flexible logging features to using named logging system of ros/log4cxx. +* Reset odometry also works for heading (gyro). +* Do not use robot_pose_ekf; use imu for heading and encoders for position. + +0.4.0 (2013-08-09) +------------------ +* Windows compatible. +* Update doxygen documentation for using wstool and for windows compilation. +* New scripts to help serve firmware and windows downloads from our file server. +* Delay demo program finish so kobuki can beep alive. +* Serial connection made much more robust. +* Install using wstool +* Update firmware_changelog.md with latest verions and rewrite with for markdown formatting. + + +Previous versions, bugfixing +============================ + +Available in ROS wiki: http://ros.org/wiki/kobuki/ChangeList diff --git a/ros2_ws/src/kobuki_core/CMakeLists.txt b/ros2_ws/src/kobuki_core/CMakeLists.txt new file mode 100644 index 0000000..9fce521 --- /dev/null +++ b/ros2_ws/src/kobuki_core/CMakeLists.txt @@ -0,0 +1,69 @@ +############################################################################## +# Cmake +############################################################################## + +cmake_minimum_required(VERSION 3.5) +project(kobuki_core) + +# Turn -isystem off. Actually like to see warnings from underlying packages +# and regardless, have run into trouble because of the ordering it induces. +set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) + +############################################################################## +# Find Packages +############################################################################## + +find_package(ament_cmake_ros REQUIRED) + +find_package(ecl_build REQUIRED) +find_package(ecl_command_line REQUIRED) +find_package(ecl_config REQUIRED) +find_package(ecl_console REQUIRED) +find_package(ecl_converters REQUIRED) +find_package(ecl_devices REQUIRED) +find_package(ecl_geometry REQUIRED) +find_package(ecl_threads REQUIRED) +find_package(ecl_mobile_robot REQUIRED) +find_package(ecl_sigslots REQUIRED) +find_package(ecl_time REQUIRED) + +############################################################################## +# Platform Configuration +############################################################################## + +ament_package_xml() +ecl_enable_cxx14_compiler() +ecl_enable_cxx_warnings() + +############################################################################## +# Sources +############################################################################## + +add_subdirectory(include) +add_subdirectory(src) + +############################################################################## +# Exports +############################################################################## + +ament_export_targets(${PROJECT_NAME}) +ament_export_dependencies( + ecl_config + ecl_console + ecl_converters + ecl_devices + ecl_geometry + ecl_mobile_robot + ecl_sigslots + ecl_threads + ecl_time + ) + +install( + DIRECTORY include/ + DESTINATION include +) +ament_export_include_directories(include) +# TODO: deprecate this line post 'ardent' (been fixed upstream) +ament_export_libraries(${PROJECT_NAME}) +ament_package() diff --git a/ros2_ws/src/kobuki_core/LICENSE b/ros2_ws/src/kobuki_core/LICENSE new file mode 100644 index 0000000..cf09699 --- /dev/null +++ b/ros2_ws/src/kobuki_core/LICENSE @@ -0,0 +1,32 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos, +# Marcus Liebhardt, Younghun Ju, Jihoon Lee +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Yujin Robot nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. diff --git a/ros2_ws/src/kobuki_core/README.md b/ros2_ws/src/kobuki_core/README.md new file mode 100644 index 0000000..e9c4e5b --- /dev/null +++ b/ros2_ws/src/kobuki_core/README.md @@ -0,0 +1,18 @@ +# Kobuki Core + +![Kobuki Logo](resources/kobuki.png) + +---- + +The **Kobuki Core** stack consists of c++ libraries and utilities for working with a [Kobuki Robot](https://iclebo-kobuki.readthedocs.io/en/latest/). + +---- + +## Documentation + +The Kobuki ecosystem contains several repositories and packages that get bundled together. Refer to the documentation release relevant to the branch/version of *kobuki_core* you are using: + +| Kobuki Core Branch | Kobuki Documentation Release | +|:------------------:|:----------------------------:| +| [devel](https://github.com/kobuki-base/kobuki_core/tree/devel) | https://kobuki.readthedocs.io/en/devel/ | +| [release/1.2.x](https://github.com/kobuki-base/kobuki_core/tree/release/1.2.x) | https://kobuki.readthedocs.io/en/release-1.0.x/ | diff --git a/ros2_ws/src/kobuki_core/debian/postinst b/ros2_ws/src/kobuki_core/debian/postinst new file mode 100755 index 0000000..1c0b9f3 --- /dev/null +++ b/ros2_ws/src/kobuki_core/debian/postinst @@ -0,0 +1,67 @@ +#!/bin/sh +# postinst script for kobuki udev rules (part of the kobuki_core package) +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * `configure' +# * `abort-upgrade' +# * `abort-remove' `in-favour' +# +# * `abort-remove' +# * `abort-deconfigure' `in-favour' +# `removing' +# +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + +# source debconf library +. /usr/share/debconf/confmodule + +OLDUDEV="/etc/udev/rules.d/60-kobuki.rules" + +# Are we running in a Docker Environment? +docker_cnt=$(awk '$2 == "(1,"' /proc/1/sched | wc -l) +# docker_cnt == 0 we are in a docker environment + +case "$1" in + + configure) + # Set FORCE_UDEV_IN_DOCKER to non-empty to override + if [ ${docker_cnt} -eq 0 -a -z "${FORCE_UDEV_IN_DOCKER}" ] + then + echo "INFO: Docker environment not supported for udevadm; skipping." + else + # Enforce the newly installed udev rules + (udevadm control --reload-rules && udevadm trigger) || true + fi + + # Emit a warning to the user - tell them to clean up a manually installed rule + if [ -f ${OLDUDEV} ] + then + echo "WARNING: Locally installed and conflicting kobuki udev rule will be removed:" + echo " sudo rm -f ${OLDUDEV}" + fi + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + exit 0 + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; + +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +db_stop + +exit 0 diff --git a/ros2_ws/src/kobuki_core/debian/udev b/ros2_ws/src/kobuki_core/debian/udev new file mode 120000 index 0000000..12786c4 --- /dev/null +++ b/ros2_ws/src/kobuki_core/debian/udev @@ -0,0 +1 @@ +../60-kobuki.rules \ No newline at end of file diff --git a/ros2_ws/src/kobuki_core/doc/Makefile b/ros2_ws/src/kobuki_core/doc/Makefile new file mode 100644 index 0000000..d56f14e --- /dev/null +++ b/ros2_ws/src/kobuki_core/doc/Makefile @@ -0,0 +1,13 @@ +# Makefile for Doxygen documentation +# +BUILDDIR=generated + +help: + @echo "Please use \`make ' where is one of" + @echo " dox all variants of doxygen documentation" + +dox: + doxygen doxy.conf + +clean: + rm -rf $(BUILDDIR) diff --git a/ros2_ws/src/kobuki_core/doc/doxy.conf b/ros2_ws/src/kobuki_core/doc/doxy.conf new file mode 100644 index 0000000..8f1d032 --- /dev/null +++ b/ros2_ws/src/kobuki_core/doc/doxy.conf @@ -0,0 +1,2582 @@ +# Doxyfile 1.8.17 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = Kobuki + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = 1.0.0 + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = "C++ API for the Kobuki research robot" + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = images/logo_kobuki.png + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = ./generated + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all generated output in the proper direction. +# Possible values are: None, LTR, RTL and Context. +# The default value is: None. + +OUTPUT_TEXT_DIRECTION = None + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines (in the resulting output). You can put ^^ in the value part of an +# alias to insert a newline as if a physical newline was in the original file. +# When you need a literal { or } or , in the value part of an alias you have to +# escape them by means of a backslash (\), this can lead to conflicts with the +# commands \{ and \} for these it is advised to use the version @{ and @} or use +# a double escape (\\{ and \\}) + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, JavaScript, +# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, +# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is +# Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 0 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# declarations. If set to NO, these declarations will be included in the +# documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# (including Cygwin) ands Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = NO + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. If +# EXTRACT_ALL is set to YES then this flag will automatically be disabled. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = english/en_installation_linux.dox \ + english/en_ftdi.dox \ + english/en_getting_started.dox \ + english/en_sigslots.dox \ + english/en_simple_example.dox \ + english/en_appendix_parameters.dox \ + english/en_appendix_protocol.dox \ + english/en_version.dox \ + ../ + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: https://www.gnu.org/software/libiconv/) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment), +# *.doc (to be provided as doxygen C comment), *.txt (to be provided as doxygen +# C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f, *.for, *.tcl, *.vhd, +# *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the +# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the +# cost of reduced performance. This can be particularly helpful with template +# rich C++ code for which doxygen's built-in parser lacks the necessary type +# information. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse_libclang=ON option for CMake. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = + +# If clang assisted parsing is enabled you can provide the clang parser with the +# path to the compilation database (see: +# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) used when the files +# were built. This is equivalent to specifying the "-p" option to a clang tool, +# such as clang-check. These options will then be passed to the parser. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse_libclang=ON option for CMake. + +CLANG_DATABASE_PATH = + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via JavaScript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have JavaScript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: https://developer.apple.com/xcode/), introduced with OSX +# 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = YES + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands +# to create new LaTeX commands to be used in formulas as building blocks. See +# the section "Including formulas" for details. + +FORMULA_MACROFILE = + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side JavaScript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. +# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /