Go to battery charger

Another alternative solution

As we have our code straightened out, we can call it by timer as we did above. The "spin" function simply calls "sleep" to allow the code to run. Again, in theory this should work, but it will not call your subscribers!

As an alternative, we can run our own "spin" function, it makes the code easier to understand, also, we can perform extra tasks between "spins" without using Executors.

To do it, we need to remove timer, as now we are going to call our code directly:

                    #self.timer = self.create_timer(timer_period, self.navigate_to_waypoints_or_charger)
                

Then we need to implement the loop in a main function:

                    def main(args=None):

                    try:  
                        rclpy.init(args=args)
                        
                        navigator = ChargerNavigator()
                
                        try:
                            while(True):
                                bResult = navigator.navigate_to_waypoints_or_charger()
                                if(not bResult):
                                    break
                                time.sleep(0.1)
                        finally:
                            navigator.destroy_node()
                 
                    finally:
                        rclpy.shutdown()   

                    if __name__ == '__main__':
                    main()
                

Note that we now have a return value that can be used to determine if the program performed without errors. A nice extra bonus!
TBD: By the way, a proper way of using sleep function in this cycle would be using ROS2 version of it. The ROS2 sleep waits not for the specified duration, but for the time remaining. Let's say you want your code to run every 0.1 second. Let's also say that your code itself takes 0.05 seconds to execute. Then ROS2 version of "sleep(0.1)" will only wait for 0.05 seconds, so the cycle (your code plus your "sleep") takes 0.1 seconds.

(C) snowcron.com, all rights reserved

Please read the disclaimer