MRPT  1.9.9
CAbstractNavigator.h
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 #pragma once
10 
18 #include <mrpt/obs/obs_frwds.h>
19 
20 #include <mutex>
21 #include <memory> // unique_ptr
22 #include <functional>
23 
24 namespace mrpt::nav
25 {
26 /** This is the base class for any reactive/planned navigation system. See
27  * derived classes.
28  *
29  * How to use:
30  * - A class derived from `CRobot2NavInterface` with callbacks must be defined
31  * by the user and provided to the constructor.
32  * - `navigationStep()` must be called periodically in order to effectively run
33  * the navigation. This method will internally call the callbacks to gather
34  * sensor data and robot positioning data.
35  *
36  * It implements the following state machine (see
37  * CAbstractNavigator::getCurrentState() ), taking into account the extensions
38  * described in CWaypointsNavigator
39  * \dot
40  * digraph CAbstractNavigator_States {
41  * IDLE; NAVIGATING; SUSPENDED; NAV_ERROR;
42  * IDLE -> NAVIGATING [ label="CAbstractNavigator::navigate()"];
43  * IDLE -> NAVIGATING [ label="CWaypointsNavigator::navigateWaypoints()" ];
44  * NAVIGATING -> IDLE [ label="Final target reached" ];
45  * NAVIGATING -> IDLE [ label="CAbstractNavigator::cancel()" ];
46  * NAVIGATING -> NAV_ERROR [ label="Upon sensor errors, timeout,..." ];
47  * NAVIGATING -> SUSPENDED [ label="CAbstractNavigator::suspend()" ];
48  * SUSPENDED -> NAVIGATING [ label="CAbstractNavigator::resume()" ];
49  * NAV_ERROR -> IDLE [ label="CAbstractNavigator::resetNavError()" ];
50  * }
51  * \enddot
52  *
53  * \sa CWaypointsNavigator, CReactiveNavigationSystem, CRobot2NavInterface, all
54  * children classes
55  * \ingroup nav_reactive
56  */
58 {
59  public:
60  /** ctor */
61  CAbstractNavigator(CRobot2NavInterface& robot_interface_impl);
62  /** dtor */
63  virtual ~CAbstractNavigator();
64 
65  /** Individual target info in CAbstractNavigator::TNavigationParamsBase and
66  * derived classes */
67  struct TargetInfo
68  {
69  /** Coordinates of desired target location. Heading may be ignored by
70  * some reactive implementations. */
72  /** (Default="map") Frame ID in which target is given. Optional, use
73  * only for submapping applications. */
75  /** (Default=0.5 meters) Allowed distance to target in order to end the
76  * navigation. */
78  /** (Default=false) Whether the \a target coordinates are in global
79  * coordinates (false) or are relative to the current robot pose (true).
80  */
82  /** (Default=.05) Desired relative speed (wrt maximum speed), in range
83  * [0,1], of the vehicle at target. Holonomic nav methods will perform
84  * "slow down" approaching target only if this is "==.0". Intermediary
85  * values will be honored only by the higher-level navigator, based on
86  * straight-line Euclidean distances. */
88  bool targetIsIntermediaryWaypoint; // !< (Default=false) If true, event
89  // callback
90  // `sendWaypointReachedEvent()` will
91  // be called instead of
92  // `sendNavigationEndEvent()`
93 
94  TargetInfo();
95  /** Gets navigation params as a human-readable format */
96  std::string getAsText() const;
97  bool operator==(const TargetInfo& o) const;
98  bool operator!=(const TargetInfo& o) const { return !(*this == o); }
99  };
100 
101  /** Base for all high-level navigation commands. See derived classes */
103  {
105  /** Gets navigation params as a human-readable format */
106  virtual std::string getAsText() const = 0;
107 
108  protected:
109  friend bool operator==(
111  virtual bool isEqual(const TNavigationParamsBase& o) const = 0;
112  };
113 
114  /** The struct for configuring navigation requests. Used in
115  * CAbstractPTGBasedReactive::navigate() */
117  {
118  /** Navigation target */
120 
121  /** Gets navigation params as a human-readable format */
122  virtual std::string getAsText() const override;
123  virtual std::unique_ptr<TNavigationParams> clone() const
124  {
125  return std::make_unique<TNavigationParams>(*this);
126  }
127 
128  protected:
129  virtual bool isEqual(const TNavigationParamsBase& o) const override;
130  };
131 
132  /** \name Navigation control API
133  * @{ */
134 
135  /** Loads all params from a file. To be called before initialize().
136  * Each derived class *MUST* load its own parameters, and then call *ITS
137  * PARENT'S* overriden method to ensure all params are loaded. */
138  virtual void loadConfigFile(const mrpt::config::CConfigFileBase& c);
139  /** Saves all current options to a config file.
140  * Each derived class *MUST* save its own parameters, and then call *ITS
141  * PARENT'S* overriden method to ensure all params are saved. */
142  virtual void saveConfigFile(mrpt::config::CConfigFileBase& c) const;
143 
144  /** Must be called before any other navigation command */
145  virtual void initialize() = 0;
146  /** This method must be called periodically in order to effectively run the
147  * navigation */
148  virtual void navigationStep();
149 
150  /** Navigation request to a single target location. It starts a new
151  * navigation.
152  * \param[in] params Pointer to structure with navigation info (its
153  * contents will be copied, so the original can be freely destroyed upon
154  * return if it was dynamically allocated.)
155  * \note A pointer is used so the passed object can be polymorphic with
156  * derived types.
157  */
158  virtual void navigate(const TNavigationParams* params);
159 
160  /** Cancel current navegation. */
161  virtual void cancel();
162  /** Continues with suspended navigation. \sa suspend */
163  virtual void resume();
164  /** Suspend current navegation. \sa resume */
165  virtual void suspend();
166  /** Resets a `NAV_ERROR` state back to `IDLE` */
167  virtual void resetNavError();
168 
169  /** The different states for the navigation system. */
170  enum TState
171  {
172  IDLE = 0,
176  };
177 
178  /** Returns the current navigator state. */
179  inline TState getCurrentState() const { return m_navigationState; }
180  /** Sets a user-provided frame transformer object; used only if providing
181  * targets in a frame ID
182  * different than the one in which robot odometry is given (both IDs
183  * default to `"map"`).
184  */
185  void setFrameTF(
186  const std::weak_ptr<mrpt::poses::FrameTransformer<2>>& frame_tf);
187 
188  /** Get the current frame tf object (defaults to nullptr) \sa setFrameTF */
189  std::weak_ptr<mrpt::poses::FrameTransformer<2>> getFrameTF() const
190  {
191  return m_frame_tf;
192  }
193 
194  /** @}*/
195 
197  {
198  /** Default value=0, means use the "targetAllowedDistance" passed by the
199  * user in the navigation request. */
201  /** navigator timeout (seconds) [Default=30 sec] */
203  /** (Default value=0.6) When closer than this distance, check if the
204  * target is blocked to abort navigation with an error. */
206  /** (Default=3) How many steps should the condition for
207  * dist_check_target_is_blocked be fulfilled to raise an event */
209 
210  virtual void loadFromConfigFile(
212  const std::string& s) override;
213  virtual void saveToConfigFile(
215  const std::string& s) const override;
217  };
218 
220 
221  /** Gives access to a const-ref to the internal time logger used to estimate
222  * delays \sa getTimeLogger() in derived classes */
224  {
225  return m_timlog_delays;
226  }
227 
228  private:
229  /** Last internal state of navigator: */
231  /** Will be false until the navigation end is sent, and it is reset with
232  * each new command */
235 
236  /** Called before starting a new navigation. Internally, it calls to
237  * child-implemented onStartNewNavigation() */
239 
240  protected:
241  /** Events generated during navigationStep(), enqueued to be called at the
242  * end of the method execution to avoid user code to change the navigator
243  * state. */
244  std::vector<std::function<void(void)>> m_pending_events;
245 
247 
248  /** To be implemented in derived classes */
249  virtual void performNavigationStep() = 0;
250 
251  /** Called whenever a new navigation has been started. Can be used to reset
252  * state variables, etc. */
253  virtual void onStartNewNavigation() = 0;
254 
255  /** Called after each call to CAbstractNavigator::navigate() */
256  virtual void onNavigateCommandReceived();
257 
258  /** Call to the robot getCurrentPoseAndSpeeds() and updates members
259  * m_curPoseVel accordingly.
260  * If an error is returned by the user callback, first, it calls
261  * robot.stop() ,then throws an std::runtime_error exception. */
263 
264  /** Factorization of the part inside navigationStep(), for the case of state
265  * being NAVIGATING.
266  * Performs house-hold tasks like raising events in case of starting/ending
267  * navigation, timeout reaching destination, etc.
268  * `call_virtual_nav_method` can be set to false to avoid calling the
269  * virtual method performNavigationStep()
270  */
271  virtual void performNavigationStepNavigating(
272  bool call_virtual_nav_method = true);
273 
274  /** Does the job of navigate(), except the call to
275  * onNavigateCommandReceived() */
277 
278  /** Stops the robot and set navigation state to error */
279  void doEmergencyStop(const std::string& msg);
280 
281  /** Default: forward call to m_robot.changeSpeed(). Can be overriden. */
282  virtual bool changeSpeeds(const mrpt::kinematics::CVehicleVelCmd& vel_cmd);
283  /** Default: forward call to m_robot.changeSpeedsNOP(). Can be overriden. */
284  virtual bool changeSpeedsNOP();
285  /** Default: forward call to m_robot.stop(). Can be overriden. */
286  virtual bool stop(bool isEmergencyStop);
287 
288  /** Default implementation: check if target_dist is below the accepted
289  * distance.
290  * If true is returned here, the end-of-navigation event will be sent out
291  * (only for non-intermediary targets).
292  */
293  virtual bool checkHasReachedTarget(const double targetDist) const;
294 
295  /** Checks whether the robot shape, when placed at the given pose (relative
296  * to the current pose),
297  * is colliding with any of the latest known obstacles.
298  * Default implementation: always returns false. */
300  const mrpt::math::TPose2D& relative_robot_pose) const;
301 
302  /** Current internal state of navigator: */
304  /** Current navigation parameters */
305  std::unique_ptr<TNavigationParams> m_navigationParams;
306 
307  /** The navigator-robot interface. */
309 
310  /** Optional, user-provided frame transformer. */
311  std::weak_ptr<mrpt::poses::FrameTransformer<2>> m_frame_tf;
312 
313  /** mutex for all navigation methods */
314  std::recursive_mutex m_nav_cs;
315 
317  {
320  /** raw odometry (frame does not match to "pose", but is expected to be
321  * smoother in the short term). */
324  /** map frame ID for `pose` */
326  TRobotPoseVel();
327  };
328 
329  /** Current robot pose (updated in CAbstractNavigator::navigationStep() ) */
333  /** Latest robot poses (updated in CAbstractNavigator::navigationStep() ) */
335 
336  /** Time logger to collect delay-related stats */
338 
339  /** For sending an alarm (error event) when it seems that we are not
340  * approaching toward the target in a while... */
343 
344  public:
346 };
347 
348 bool operator==(
351 }
353 using namespace mrpt::nav;
359 
360 
double m_badNavAlarm_minDistTarget
For sending an alarm (error event) when it seems that we are not approaching toward the target in a w...
std::recursive_mutex m_nav_cs
mutex for all navigation methods
virtual std::unique_ptr< TNavigationParams > clone() const
TRobotPoseVel m_curPoseVel
Current robot pose (updated in CAbstractNavigator::navigationStep() )
virtual void loadConfigFile(const mrpt::config::CConfigFileBase &c)
Loads all params from a file.
mrpt::system::CTimeLogger m_timlog_delays
Time logger to collect delay-related stats.
This class stores a time-stamped trajectory in SE(2) (mrpt::math::TPose2D poses). ...
This is a virtual base class for sets of options than can be loaded from and/or saved to configuratio...
void setFrameTF(const std::weak_ptr< mrpt::poses::FrameTransformer< 2 >> &frame_tf)
Sets a user-provided frame transformer object; used only if providing targets in a frame ID different...
Base for all high-level navigation commands.
float targetAllowedDistance
(Default=0.5 meters) Allowed distance to target in order to end the navigation.
void updateCurrentPoseAndSpeeds()
Call to the robot getCurrentPoseAndSpeeds() and updates members m_curPoseVel accordingly.
bool targetIsRelative
(Default=false) Whether the target coordinates are in global coordinates (false) or are relative to t...
#define MRPT_MAKE_ALIGNED_OPERATOR_NEW
Put this macro inside any class with members that require {16,32,64}-byte memory alignment (e...
double dist_check_target_is_blocked
(Default value=0.6) When closer than this distance, check if the target is blocked to abort navigatio...
GLdouble s
Definition: glext.h:3676
virtual void navigationStep()
This method must be called periodically in order to effectively run the navigation.
std::string pose_frame_id
map frame ID for pose
virtual bool changeSpeeds(const mrpt::kinematics::CVehicleVelCmd &vel_cmd)
Default: forward call to m_robot.changeSpeed().
std::weak_ptr< mrpt::poses::FrameTransformer< 2 > > getFrameTF() const
Get the current frame tf object (defaults to nullptr)
virtual bool changeSpeedsNOP()
Default: forward call to m_robot.changeSpeedsNOP().
virtual bool isEqual(const TNavigationParamsBase &o) const =0
TState m_navigationState
Current internal state of navigator:
Virtual base for velocity commands of different kinematic models of planar mobile robot...
2D twist: 2D velocity vector (vx,vy) + planar angular velocity (omega)
virtual void performNavigationStep()=0
To be implemented in derived classes.
bool operator==(const CAbstractNavigator::TNavigationParamsBase &, const CAbstractNavigator::TNavigationParamsBase &)
The struct for configuring navigation requests.
mrpt::Clock::time_point TTimeStamp
A system independent time type, it holds the the number of 100-nanosecond intervals since January 1...
Definition: datetime.h:40
CAbstractNavigator(CRobot2NavInterface &robot_interface_impl)
ctor
This class allows loading and storing values and vectors of different types from a configuration text...
TState
The different states for the navigation system.
virtual void loadFromConfigFile(const mrpt::config::CConfigFileBase &c, const std::string &s) override
This method load the options from a ".ini"-like file or memory-stored string list.
double dist_to_target_for_sending_event
Default value=0, means use the "targetAllowedDistance" passed by the user in the navigation request...
double targetDesiredRelSpeed
(Default=.05) Desired relative speed (wrt maximum speed), in range [0,1], of the vehicle at target...
TState getCurrentState() const
Returns the current navigator state.
virtual void onNavigateCommandReceived()
Called after each call to CAbstractNavigator::navigate()
const mrpt::system::CTimeLogger & getDelaysTimeLogger() const
Gives access to a const-ref to the internal time logger used to estimate delays.
std::string target_frame_id
(Default="map") Frame ID in which target is given.
const GLubyte * c
Definition: glext.h:6313
Versatile class for consistent logging and management of output messages.
virtual void resetNavError()
Resets a NAV_ERROR state back to IDLE
std::unique_ptr< TNavigationParams > m_navigationParams
Current navigation parameters.
void internal_onStartNewNavigation()
Called before starting a new navigation.
Individual target info in CAbstractNavigator::TNavigationParamsBase and derived classes.
#define MRPT_ENUM_TYPE_END()
Definition: TEnumType.h:78
virtual void onStartNewNavigation()=0
Called whenever a new navigation has been started.
GLsizei const GLchar ** string
Definition: glext.h:4101
virtual void resume()
Continues with suspended navigation.
mrpt::math::TPose2D target_coords
Coordinates of desired target location.
TState m_lastNavigationState
Last internal state of navigator:
std::vector< std::function< void(void)> > m_pending_events
Events generated during navigationStep(), enqueued to be called at the end of the method execution to...
double alarm_seems_not_approaching_target_timeout
navigator timeout (seconds) [Default=30 sec]
virtual std::string getAsText() const =0
Gets navigation params as a human-readable format.
virtual void performNavigationStepNavigating(bool call_virtual_nav_method=true)
Factorization of the part inside navigationStep(), for the case of state being NAVIGATING.
virtual void saveConfigFile(mrpt::config::CConfigFileBase &c) const
Saves all current options to a config file.
std::string getAsText() const
Gets navigation params as a human-readable format.
A versatile "profiler" that logs the time spent within each pair of calls to enter(X)-leave(X), among other stats.
void doEmergencyStop(const std::string &msg)
Stops the robot and set navigation state to error.
void processNavigateCommand(const TNavigationParams *params)
Does the job of navigate(), except the call to onNavigateCommandReceived()
TAbstractNavigatorParams params_abstract_navigator
virtual void saveToConfigFile(mrpt::config::CConfigFileBase &c, const std::string &s) const override
This method saves the options to a ".ini"-like file or memory-stored string list. ...
virtual void initialize()=0
Must be called before any other navigation command.
CRobot2NavInterface & m_robot
The navigator-robot interface.
virtual bool isEqual(const TNavigationParamsBase &o) const override
virtual bool checkCollisionWithLatestObstacles(const mrpt::math::TPose2D &relative_robot_pose) const
Checks whether the robot shape, when placed at the given pose (relative to the current pose)...
Lightweight 2D pose.
virtual void cancel()
Cancel current navegation.
bool operator==(const TargetInfo &o) const
virtual void suspend()
Suspend current navegation.
std::weak_ptr< mrpt::poses::FrameTransformer< 2 > > m_frame_tf
Optional, user-provided frame transformer.
friend bool operator==(const TNavigationParamsBase &, const TNavigationParamsBase &)
int hysteresis_check_target_is_blocked
(Default=3) How many steps should the condition for dist_check_target_is_blocked be fulfilled to rais...
virtual bool checkHasReachedTarget(const double targetDist) const
Default implementation: check if target_dist is below the accepted distance.
mrpt::poses::CPose2DInterpolator m_latestOdomPoses
bool m_navigationEndEventSent
Will be false until the navigation end is sent, and it is reset with each new command.
The pure virtual interface between a real or simulated robot and any CAbstractNavigator-derived class...
mrpt::system::TTimeStamp m_badNavAlarm_lastMinDistTime
#define MRPT_ENUM_TYPE_BEGIN(_ENUM_TYPE_WITH_NS)
Definition: TEnumType.h:62
This is the base class for any reactive/planned navigation system.
GLenum const GLfloat * params
Definition: glext.h:3534
mrpt::poses::CPose2DInterpolator m_latestPoses
Latest robot poses (updated in CAbstractNavigator::navigationStep() )
virtual std::string getAsText() const override
Gets navigation params as a human-readable format.
bool operator!=(const TargetInfo &o) const
mrpt::math::TPose2D rawOdometry
raw odometry (frame does not match to "pose", but is expected to be smoother in the short term)...
virtual bool stop(bool isEmergencyStop)
Default: forward call to m_robot.stop().
MRPT_FILL_ENUM_MEMBER(CAbstractNavigator, IDLE)
virtual void navigate(const TNavigationParams *params)
Navigation request to a single target location.



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 7d5e6d718 Fri Aug 24 01:51:28 2018 +0200 at lun nov 2 08:35:50 CET 2020