Main MRPT website > C++ reference for 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-2017, 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 
13 #include <mrpt/utils/CTimeLogger.h>
14 #include <mrpt/utils/TEnumType.h>
18 #include <mrpt/obs/obs_frwds.h>
19 
20 #include <mutex>
21 #include <memory> // unique_ptr
22 #include <functional>
23 
24 namespace mrpt
25 {
26 namespace nav
27 {
28 /** This is the base class for any reactive/planned navigation system. See
29  * derived classes.
30  *
31  * How to use:
32  * - A class derived from `CRobot2NavInterface` with callbacks must be defined
33  * by the user and provided to the constructor.
34  * - `navigationStep()` must be called periodically in order to effectively run
35  * the navigation. This method will internally call the callbacks to gather
36  * sensor data and robot positioning data.
37  *
38  * It implements the following state machine (see
39  * CAbstractNavigator::getCurrentState() ), taking into account the extensions
40  * described in CWaypointsNavigator
41  * \dot
42  * digraph CAbstractNavigator_States {
43  * IDLE; NAVIGATING; SUSPENDED; NAV_ERROR;
44  * IDLE -> NAVIGATING [ label="CAbstractNavigator::navigate()"];
45  * IDLE -> NAVIGATING [ label="CWaypointsNavigator::navigateWaypoints()" ];
46  * NAVIGATING -> IDLE [ label="Final target reached" ];
47  * NAVIGATING -> IDLE [ label="CAbstractNavigator::cancel()" ];
48  * NAVIGATING -> NAV_ERROR [ label="Upon sensor errors, timeout,..." ];
49  * NAVIGATING -> SUSPENDED [ label="CAbstractNavigator::suspend()" ];
50  * SUSPENDED -> NAVIGATING [ label="CAbstractNavigator::resume()" ];
51  * NAV_ERROR -> IDLE [ label="CAbstractNavigator::resetNavError()" ];
52  * }
53  * \enddot
54  *
55  * \sa CWaypointsNavigator, CReactiveNavigationSystem, CRobot2NavInterface, all
56  * children classes
57  * \ingroup nav_reactive
58  */
59 class CAbstractNavigator : public mrpt::utils::COutputLogger
60 {
61  public:
62  /** ctor */
63  CAbstractNavigator(CRobot2NavInterface& robot_interface_impl);
64  /** dtor */
65  virtual ~CAbstractNavigator();
66 
67  /** Individual target info in CAbstractNavigator::TNavigationParamsBase and
68  * derived classes */
69  struct TargetInfo
70  {
71  /** Coordinates of desired target location. Heading may be ignored by
72  * some reactive implementations. */
74  /** (Default="map") Frame ID in which target is given. Optional, use
75  * only for submapping applications. */
77  /** (Default=0.5 meters) Allowed distance to target in order to end the
78  * navigation. */
80  /** (Default=false) Whether the \a target coordinates are in global
81  * coordinates (false) or are relative to the current robot pose (true).
82  */
84  /** (Default=.05) Desired relative speed (wrt maximum speed), in range
85  * [0,1], of the vehicle at target. Holonomic nav methods will perform
86  * "slow down" approaching target only if this is "==.0". Intermediary
87  * values will be honored only by the higher-level navigator, based on
88  * straight-line Euclidean distances. */
90  bool targetIsIntermediaryWaypoint; // !< (Default=false) If true, event
91  // callback
92  // `sendWaypointReachedEvent()` will
93  // be called instead of
94  // `sendNavigationEndEvent()`
95 
96  TargetInfo();
97  /** Gets navigation params as a human-readable format */
98  std::string getAsText() const;
99  bool operator==(const TargetInfo& o) const;
100  bool operator!=(const TargetInfo& o) const { return !(*this == o); }
101  };
102 
103  /** Base for all high-level navigation commands. See derived classes */
105  {
107  /** Gets navigation params as a human-readable format */
108  virtual std::string getAsText() const = 0;
109 
110  protected:
111  friend bool operator==(
113  virtual bool isEqual(const TNavigationParamsBase& o) const = 0;
114  };
115 
116  /** The struct for configuring navigation requests. Used in
117  * CAbstractPTGBasedReactive::navigate() */
119  {
120  /** Navigation target */
122 
123  /** Gets navigation params as a human-readable format */
124  virtual std::string getAsText() const override;
125  virtual std::unique_ptr<TNavigationParams> clone() const
126  {
127  return std::make_unique<TNavigationParams>(*this);
128  }
129 
130  protected:
131  virtual bool isEqual(const TNavigationParamsBase& o) const override;
132  };
133 
134  /** \name Navigation control API
135  * @{ */
136 
137  /** Loads all params from a file. To be called before initialize().
138  * Each derived class *MUST* load its own parameters, and then call *ITS
139  * PARENT'S* overriden method to ensure all params are loaded. */
140  virtual void loadConfigFile(const mrpt::utils::CConfigFileBase& c);
141  /** Saves all current options to a config file.
142  * Each derived class *MUST* save its own parameters, and then call *ITS
143  * PARENT'S* overriden method to ensure all params are saved. */
144  virtual void saveConfigFile(mrpt::utils::CConfigFileBase& c) const;
145 
146  /** Must be called before any other navigation command */
147  virtual void initialize() = 0;
148  /** This method must be called periodically in order to effectively run the
149  * navigation */
150  virtual void navigationStep();
151 
152  /** Navigation request to a single target location. It starts a new
153  * navigation.
154  * \param[in] params Pointer to structure with navigation info (its
155  * contents will be copied, so the original can be freely destroyed upon
156  * return if it was dynamically allocated.)
157  * \note A pointer is used so the passed object can be polymorphic with
158  * derived types.
159  */
160  virtual void navigate(const TNavigationParams* params);
161 
162  /** Cancel current navegation. */
163  virtual void cancel();
164  /** Continues with suspended navigation. \sa suspend */
165  virtual void resume();
166  /** Suspend current navegation. \sa resume */
167  virtual void suspend();
168  /** Resets a `NAV_ERROR` state back to `IDLE` */
169  virtual void resetNavError();
170 
171  /** The different states for the navigation system. */
172  enum TState
173  {
174  IDLE = 0,
178  };
179 
180  /** Returns the current navigator state. */
181  inline TState getCurrentState() const { return m_navigationState; }
182  /** Sets a user-provided frame transformer object; used only if providing
183  * targets in a frame ID
184  * different than the one in which robot odometry is given (both IDs
185  * default to `"map"`).
186  * Ownership of the pointee object remains belonging to the user, which is
187  * responsible of deleting it
188  * and ensuring its a valid pointer during the lifetime of this navigator
189  * object.
190  * \todo [MRPT 2.0: Make this a weak_ptr]
191  */
193 
194  /** Get the current frame tf object (defaults to nullptr) \sa setFrameTF */
196  {
197  return m_frame_tf;
198  }
199 
200  /** @}*/
201 
203  {
204  /** Default value=0, means use the "targetAllowedDistance" passed by the
205  * user in the navigation request. */
207  /** navigator timeout (seconds) [Default=30 sec] */
209  /** (Default value=0.6) When closer than this distance, check if the
210  * target is blocked to abort navigation with an error. */
212  /** (Default=3) How many steps should the condition for
213  * dist_check_target_is_blocked be fulfilled to raise an event */
215 
216  virtual void loadFromConfigFile(
218  const std::string& s) override;
219  virtual void saveToConfigFile(
221  const std::string& s) const override;
223  };
224 
226 
227  /** Gives access to a const-ref to the internal time logger used to estimate
228  * delays \sa getTimeLogger() in derived classes */
230  {
231  return m_timlog_delays;
232  }
233 
234  private:
235  /** Last internal state of navigator: */
237  /** Will be false until the navigation end is sent, and it is reset with
238  * each new command */
241 
242  /** Called before starting a new navigation. Internally, it calls to
243  * child-implemented onStartNewNavigation() */
245 
246  protected:
247  /** Events generated during navigationStep(), enqueued to be called at the
248  * end of the method execution to avoid user code to change the navigator
249  * state. */
250  std::vector<std::function<void(void)>> m_pending_events;
251 
253 
254  /** To be implemented in derived classes */
255  virtual void performNavigationStep() = 0;
256 
257  /** Called whenever a new navigation has been started. Can be used to reset
258  * state variables, etc. */
259  virtual void onStartNewNavigation() = 0;
260 
261  /** Called after each call to CAbstractNavigator::navigate() */
262  virtual void onNavigateCommandReceived();
263 
264  /** Call to the robot getCurrentPoseAndSpeeds() and updates members
265  * m_curPoseVel accordingly.
266  * If an error is returned by the user callback, first, it calls
267  * robot.stop() ,then throws an std::runtime_error exception. */
269 
270  /** Factorization of the part inside navigationStep(), for the case of state
271  * being NAVIGATING.
272  * Performs house-hold tasks like raising events in case of starting/ending
273  * navigation, timeout reaching destination, etc.
274  * `call_virtual_nav_method` can be set to false to avoid calling the
275  * virtual method performNavigationStep()
276  */
277  virtual void performNavigationStepNavigating(
278  bool call_virtual_nav_method = true);
279 
280  /** Does the job of navigate(), except the call to
281  * onNavigateCommandReceived() */
283 
284  /** Stops the robot and set navigation state to error */
285  void doEmergencyStop(const std::string& msg);
286 
287  /** Default: forward call to m_robot.changeSpeed(). Can be overriden. */
288  virtual bool changeSpeeds(const mrpt::kinematics::CVehicleVelCmd& vel_cmd);
289  /** Default: forward call to m_robot.changeSpeedsNOP(). Can be overriden. */
290  virtual bool changeSpeedsNOP();
291  /** Default: forward call to m_robot.stop(). Can be overriden. */
292  virtual bool stop(bool isEmergencyStop);
293 
294  /** Default implementation: check if target_dist is below the accepted
295  * distance.
296  * If true is returned here, the end-of-navigation event will be sent out
297  * (only for non-intermediary targets).
298  */
299  virtual bool checkHasReachedTarget(const double targetDist) const;
300 
301  /** Checks whether the robot shape, when placed at the given pose (relative
302  * to the current pose),
303  * is colliding with any of the latest known obstacles.
304  * Default implementation: always returns false. */
306  const mrpt::math::TPose2D& relative_robot_pose) const;
307 
308  /** Current internal state of navigator: */
310  /** Current navigation parameters */
311  std::unique_ptr<TNavigationParams> m_navigationParams;
312 
313  /** The navigator-robot interface. */
315 
316  /** Optional, user-provided frame transformer.
317  * Note: We dont have ownership of the pointee object! */
319 
320  /** mutex for all navigation methods */
321  std::recursive_mutex m_nav_cs;
322 
324  {
327  /** raw odometry (frame does not match to "pose", but is expected to be
328  * smoother in the short term). */
331  /** map frame ID for `pose` */
333  TRobotPoseVel();
334  };
335 
336  /** Current robot pose (updated in CAbstractNavigator::navigationStep() ) */
340  /** Latest robot poses (updated in CAbstractNavigator::navigationStep() ) */
342 
343  /** Time logger to collect delay-related stats */
345 
346  /** For sending an alarm (error event) when it seems that we are not
347  * approaching toward the target in a while... */
350 
351  public:
353 };
354 
355 bool operator==(
358 }
359 
360 // Specializations MUST occur at the same namespace:
361 namespace utils
362 {
363 template <>
365 {
367  static void fill(bimap<enum_t, std::string>& m_map)
368  {
373  }
374 };
375 } // End of namespace
376 }
double m_badNavAlarm_minDistTarget
For sending an alarm (error event) when it seems that we are not approaching toward the target in a w...
uint64_t TTimeStamp
A system independent time type, it holds the the number of 100-nanosecond intervals since January 1...
Definition: datetime.h:32
std::recursive_mutex m_nav_cs
mutex for all navigation methods
const mrpt::utils::CTimeLogger & getDelaysTimeLogger() const
Gives access to a const-ref to the internal time logger used to estimate delays.
virtual std::unique_ptr< TNavigationParams > clone() const
TRobotPoseVel m_curPoseVel
Current robot pose (updated in CAbstractNavigator::navigationStep() )
virtual void loadConfigFile(const mrpt::utils::CConfigFileBase &c)
Loads all params from a file.
virtual void saveConfigFile(mrpt::utils::CConfigFileBase &c) const
Saves all current options to a config file.
This class stores a time-stamped trajectory in SE(2) (mrpt::math::TPose2D poses). ...
virtual void loadFromConfigFile(const mrpt::utils::CConfigFileBase &c, const std::string &s) override
This method load the options from a ".ini"-like file or memory-stored string list.
mrpt::poses::FrameTransformer< 2 > * m_frame_tf
Optional, user-provided frame transformer.
#define MRPT_MAKE_ALIGNED_OPERATOR_NEW
Definition: memory.h:134
void setFrameTF(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.
Only specializations of this class are defined for each enum type of interest.
Definition: TEnumType.h:24
bool targetIsRelative
(Default=false) Whether the target coordinates are in global coordinates (false) or are relative to t...
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
mrpt::utils::CTimeLogger m_timlog_delays
Time logger to collect delay-related stats.
virtual void saveToConfigFile(mrpt::utils::CConfigFileBase &c, const std::string &s) const override
This method saves the options to a ".ini"-like file or memory-stored string list. ...
virtual bool changeSpeeds(const mrpt::kinematics::CVehicleVelCmd &vel_cmd)
Default: forward call to m_robot.changeSpeed().
virtual bool changeSpeedsNOP()
Default: forward call to m_robot.changeSpeedsNOP().
This class allows loading and storing values and vectors of different types from a configuration text...
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.
CAbstractNavigator(CRobot2NavInterface &robot_interface_impl)
ctor
TState
The different states for the navigation system.
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()
std::string target_frame_id
(Default="map") Frame ID in which target is given.
const GLubyte * c
Definition: glext.h:6313
virtual void resetNavError()
Resets a NAV_ERROR state back to IDLE
A bidirectional version of std::map, declared as bimap<KEY,VALUE> and which actually contains two std...
Definition: bimap.h:34
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.
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.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
virtual void performNavigationStepNavigating(bool call_virtual_nav_method=true)
Factorization of the part inside navigationStep(), for the case of state being NAVIGATING.
std::string getAsText() const
Gets navigation params as a human-readable format.
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 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.
A versatile "profiler" that logs the time spent within each pair of calls to enter(X)-leave(X), among other stats.
Definition: CTimeLogger.h:45
virtual void cancel()
Cancel current navegation.
bool operator==(const TargetInfo &o) const
virtual void suspend()
Suspend current navegation.
friend bool operator==(const TNavigationParamsBase &, const TNavigationParamsBase &)
void insert(const KEY &k, const VALUE &v)
Insert a new pair KEY<->VALUE in the bi-map.
Definition: bimap.h:75
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
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
This is a virtual base class for sets of options than can be loaded from and/or saved to configuratio...
mrpt::math::TPose2D rawOdometry
raw odometry (frame does not match to "pose", but is expected to be smoother in the short term)...
const mrpt::poses::FrameTransformer< 2 > * getFrameTF() const
Get the current frame tf object (defaults to nullptr)
virtual bool stop(bool isEmergencyStop)
Default: forward call to m_robot.stop().
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: ae4571287 Thu Nov 23 00:06:53 2017 +0100 at dom oct 27 23:51:55 CET 2019