Programming Robots with ROS Morgan Quigley, Brian Gerkey, and William D Smart Programming Robots with ROS by Morgan Quigley, Brian Gerkey, and William D Smart Copyright © 2016 Morgan Quigley, Brian Gerkey, and William D Smart All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://safaribooksonline.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Acquisitions Editor: Mike Loukides Editors: Meghan Blanchette and Dawn Schanafelt Production Editor: Matthew Hacker Copyeditor: Rachel Head Proofreader: Amanda Kersey Indexer: WordCo Indexing Services, Inc Interior Designer: David Futato Cover Designer: Ellie Volckhausen Illustrator: Rebecca Demarest December 2015: First Edition Revision History for the First Edition 2015-11-18 First Release See http://oreilly.com/catalog/errata.csp?isbn=9781449323899 for release details The O’Reilly logo is a registered trademark of O’Reilly Media, Inc Programming Robots with ROS, the cover image of a Salim Ali’s fruit bat, and related trade dress are trademarks of O’Reilly Media, Inc While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work Use of the information and instructions contained in this work is at your own risk If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights 978-1-4493-2389-9 [LSI] Preface ROS, the Robot Operating System, is an open source framework for getting robots to do things ROS is meant to serve as a common software platform for people who are building and using robots This common platform lets people share code and ideas more readily and, perhaps more importantly, means that you do not have to spend years writing software infrastructure before your robots start moving! ROS has been remarkably successful At the time of writing, in the official distribution of ROS, there are over 2,000 software packages, written and maintained by almost 600 people Approximately 80 commercially available robots are supported, and we can find at least 1,850 academic papers that mention ROS We no longer have to write everything from scratch, especially if we’re working with one of the many robots that support ROS, and can spend more time thinking about robotics, rather than bit-fiddling and device drivers ROS consists of a number of parts: A set of drivers that let you read data from sensors and send commands to motors and other actuators, in an abstracted, well-defined format A wide variety of popular hardware is supported, including a growing number of commercially available robot systems A large and growing collection of fundamental robotics algorithms that allow you to build maps of the world, navigate around it, represent and interpret sensor data, plan motions, manipulate objects, and do a lot of other stuff ROS has become very popular in the robotics research community, and a lot of cutting-edge algorithms are now available in ROS All of the computational infrastructure that allows you to move data around, to connect the various components of a complex robot system, and to incorporate your own algorithms ROS is inherently distributed and allows you to split the workload across multiple computers seamlessly A large set of tools that make it easy to visualize the state of the robot and the algorithms, debug faulty behaviors, and record sensor data Debugging robot software is notoriously difficult, and this rich set of tools is one of the things that make ROS as powerful as it is Finally, the larger ROS ecosystem includes an extensive set of resources, such as a wiki that documents many of the aspects of the framework, a question-and-answer site where you can ask for help and share what you’ve learned, and a thriving community of users and developers So, why should you learn ROS? The short answer is because it will save you time ROS provides all the parts of a robot software system that you would otherwise have to write It allows you to focus on the parts of the system that you care about, without worrying about the parts that you don’t care about Why should you read this book? There’s a lot of material on the ROS wiki, including detailed tutorials for many aspects of the framework A thriving user community is ready to answer your questions on http://answers.ros.org Why not just learn ROS from these resources? What we’ve tried to do in this book is to lay things out in a more ordered way and to give comprehensive examples of how you can use ROS to do interesting things with real and simulated robots We’ve also tried to include tips and hints about how to structure your code, how to debug your code when it causes the robot to do something unexpected, and how to become part of the ROS community There’s a fair amount of complexity in ROS, especially if you’re not a seasoned programmer; distributed computation, multithreading, event-driven programming, and a host of other concepts lie at the heart of the system If you’re not already familiar with at least some of these, ROS can have a daunting learning curve This book is an attempt to flatten out that curve a bit by introducing you to the basics of ROS and giving you some practical examples of how to use it for real applications on real (and simulated) robots Who Should Read This Book? If you want to make your robots do things in the real world, but don’t want to spend time reinventing the wheel, then this book is for you ROS includes all of the computational infrastructure you’ll need to get your robots up and running and enough robotics algorithms to get them doing interesting things quickly If you’re interested in some particular aspect, like path planning, and want to investigate it in the context of a larger robot system, then this book is for you We’ll show you how to get your robot doing interesting things using the infrastructure and algorithms in ROS and how to swap out some of the existing algorithms for your own If you want to get an introduction to the basic mechanisms of ROS and an overview of some of the things that are possible, but you’re a bit daunted by the scale of the information on the wiki, then this book is for you We’ll give you a tour of the basic mechanisms and tools in ROS and concrete examples of complete systems that you can build on and adapt for sensor measurements on demand, Design 4: Sensor Measurements on Demand for streaming measurements over a topic, Design 2: Streaming Measurements over a Topic for streaming measurements published at a fixed rate, Design 2: Streaming Measurements over a Topic with actuators, Designing the ROS Wrapper-Designing the ROS Wrapper with sensors, Designing the ROS Wrapper X XML and Gazebo, Modeling a Chessboard and launch files, roslaunch and Python template engine, Stockroom Simulation-Stockroom Simulation and roslaunch, Starting Many Nodes: roslaunch and URDF (see URDF (Unified Robot Description Format)) Y YAML and maps, Maps in ROS and parameter values, Parameters: rosparam and rostopic, Motion Generator and rostopic pub, Introspection: rosnode, rostopic, rosmsg, rosservice, and rossrv for parameter values, Parameters: rosparam yaw rate, Teleop-bot About the Authors Morgan Quigley is a cofounder of the Open Source Robotics Foundation (OSRF), which develops and maintains the Robot Operating System (ROS) He came to OSRF after receiving a PhD in computer science at Stanford University, where he created one of the ancestors of ROS as part of the Stanford AI Robot (STAIR) project in 2006 and 2007 As it became clear that the future of robotics software was in collaborative development, this effort led him to cofound the ROS project with many other engineers His research interests include robot software systems, open source software and firmware, embedded systems design, mechatronics, and sensor design Brian Gerkey is cofounder and CEO of OSRF Prior to joining OSRF, Brian was Director of Open Source Development at Willow Garage Previously, Brian was a Computer Scientist in the Artificial Intelligence Center at SRI, and before that, a postdoctoral research fellow in the Artificial Intelligence Lab at Stanford University Brian received his PhD in computer science from the University of Southern California (USC) in 2003, his MS in computer science from USC in 2000, and his BSE in computer engineering, with a secondary major in mathematics and a minor in robotics and automation, from Tulane University in 1998 Since 2008, Brian has worked on the ROS Project, which develops and releases one of the most widely used robot software platforms in robotics research and education (and soon industry) He is founding and former lead developer on the open source Player Project, which continues to maintain widely used robot simulation and development tools Bill Smart is an associate professor at Oregon State University, where he codirects the Robotics program His research interests span the areas of mobile robotics, machine learning, human–robot interaction, and the interaction between robotics and the law Bill has been writing software for robots for over two decades, and doing active research and development of robot software architectures for over 15 years At Oregon State University, he codirects the Robotics program and teaches classes in robotics and computer programming at both the undergraduate and graduate levels He has been a ROS user since the beginning and was involved in some of the early planning workshops for the system In 2010–11, he spent a 15-month sabbatical at Willow Garage, developing software for PR2 robots and enjoying the weather in California Colophon The animal on the cover of Programming Robots with ROS is a Salim Ali’s fruit bat (Latidens salimalii) Named after the famed Indian ornithologist, the Salim Ali’s fruit bat remains a rare species about which little is known, more than 60 years since it was first collected and mistaken for a short-nosed fruit bat Confined to rainforests at the southern tip of the Indian Peninsula, in the vicinity of the Western Ghats mountain range that runs along the Arabian Sea, the Salim Ali’s fruit bat is one of the more endangered species in a region acknowledged as one of the world’s most biodiverse Members of the megabat suborder to which fruit bats belong do not feed on insects Rather, they use long tongues to slurp out the nectar of flowers, or use specially adapted teeth to bite into fruit, from which they often drink only the juice The consequence of the fruit bat’s frequent interaction with flowers is a mutually beneficial relationship known as chiropterophily, in which the flowers rely on herbivorous bats to carry pollen from one flower to another The megabat’s consumption of fruit — primarily figs or the fruit of the bead tree, in the case of the Salim Ali’s fruit bat — also perform the function of dispersing seeds By mechanisms that are not clear, the fruit bat’s herbivorous nature has deprived almost all members of the Megachiroptera suborder of the ability to use echolocation It is possible, according to some research, that the economy of energy achieved by insectivorous bats, whose flight activities also seem to physiologically prepare the bat for the vocalizations that act like submarine pings in echolocation, is not as easily realized by the heartier-meal-eating and generally bigger fruit bats The megabats’ larger eyes and keener sense of smell appear to compensate The last 25 years of the Salim Ali fruit bat’s history have seen its status as a species threatened by extinction change from “rare” to “critically endangered” to the more optimistic “endangered.” Research has indicated that there is a greater population and range than was previously recorded, and efforts have been made to discourage the private owners of the land on which the bat maintains roosts from hunting it as a pest or for its rumored medicinal value However, the outlook for the survival of the species is still not bright, as humans continue to encroach on and fragment its primary habitat Many of the animals on O’Reilly covers are endangered; all of them are important to the world To learn more about how you can help, go to animals.oreilly.com The cover image is from Cassell’s Natural History The cover fonts are URW Typewriter and Guardian Sans The text font is Adobe Minion Pro; the heading font is Adobe Myriad Condensed; and the code font is Dalton Maag’s Ubuntu Mono Preface Who Should Read This Book? Who Should Not Read This Book? What You’ll Learn Prerequisites Conventions Used in This Book Using Code Examples Safari® Books Online How to Contact Us Acknowledgments I Fundamentals Introduction Brief History Philosophy Installation Summary Preliminaries The ROS Graph roscore catkin, Workspaces, and ROS Packages catkin Workspaces ROS Packages rosrun Names, Namespaces, and Remapping roslaunch The Tab Key tf: Coordinate Transforms Poses, Positions, and Orientations tf Summary Topics Publishing to a Topic Checking That Everything Works as Expected Subscribing to a Topic Checking That Everything Works as Expected Latched Topics Defining Your Own Message Types Defining a New Message Using Your New Message When Should You Make a New Message Type? Mixing Publishers and Subscribers Summary Services Defining a Service Implementing a Service Checking That Everything Works as Expected Other Ways of Returning Values from a Service Using a Service Checking That Everything Works as Expected Other Ways to Call Services Summary Actions Defining an Action Implementing a Basic Action Server Checking That Everything Works as Expected Using an Action Checking That Everything Works as Expected Implementing a More Sophisticated Action Server Using the More Sophisticated Action Checking That Everything Works as Expected Summary Robots and Simulators Subsystems Actuation: Mobile Platform Actuation: Manipulator Arm Sensors Computation Complete Robots PR2 Fetch Robonaut 2 TurtleBot Simulators Stage Gazebo Other Simulators Summary Wander-bot Creating a Package Reading Sensor Data Sensing and Actuation: Wander-bot! Summary II Moving Around Using ROS Teleop-bot Development Pattern Keyboard Driver Motion Generator Parameter Server Velocity Ramps Let’s Drive! rviz Summary Building Maps of the World Maps in ROS Recording Data with rosbag Building Maps Starting a Map Server and Looking at a Map Summary 10 Navigating About the World Localizing the Robot in a Map Getting a Good Initial Localization What’s Going on Behind the Scenes Tips for Setting a Better Initial Pose Using the ROS Navigation Stack The ROS Navigation Stack Navigating in rviz Seeing What’s Going On Navigating in Code Summary 11 Chess-bot Joints, Links, and Kinematic Chains Joint Space Inverse Kinematics The Key to Success Installing and Running a Simulated R2 Moving R2 from the Command Line Moving R2 Around a Chessboard Operating the Hand Modeling a Chessboard Playing Back a Famous Chess Game Summary III Perception and Behavior 12 Follow-bot Acquiring Images Detecting the Line Following the Line Summary 13 On Patrol Simple Patrolling State Machines State Machines in ROS Defining State Machines with smach A Slightly More Relevant Example Defining State Machines Procedurally Patrolling with State Machines A Better Way to Patrol Summary 14 Stockroom-bot Stockroom Simulation Driving to Bins Picking Up the Item Summary IV Bringing Your Own Stuff into ROS 15 Your Own Sensors and Actuators Adding Your Own Sensors A (Fake) Sensor Designing the ROS Wrapper Design 1: Periodic Measurements over a Topic Design 2: Streaming Measurements over a Topic Design 3: Streaming Measurements Published at a Fixed Rate Design 4: Sensor Measurements on Demand Adding Your Own Actuators A (Fake) Actuator Designing the ROS Wrapper Design 1: Continuous Actuation Design 2: Infrequent, Instantaneous Actuation Design 3: Infrequent, Extended Actuation Summary 16 Your Own Mobile Robot TortoiseBot ROS Message Interface Hardware Driver Modeling the Robot: URDF Simulation in Gazebo Summary 17 Your Own Mobile Robot: Part 2 Verifying Transforms Adding a Laser Sensor Configuring the Navigation Stack Using rviz to Localize and Command a Navigating Robot Summary 18 Your Own Robot Arm CougarBot ROS Message Interface Hardware Driver Modeling the Robot: URDF Simulation in Gazebo Verifying Transforms Configuring MoveIt Using rviz to Send Goals Summary 19 Adding a Software Library Make Your Robot Talk: pyttsx Action Interface Parameters Event Loops The Speech Server The Speech Client Checking That Everything Works as Expected Summary V Tips and Tricks 20 Tools The Master and Friends: roscore Parameters: rosparam Navigating the Filesystem: roscd Starting a Node: rosrun Starting Many Nodes: roslaunch Testing a Many-Node System: rostest Introspection: rosnode, rostopic, rosmsg, rosservice, and rossrv Summary 21 Debugging Robot Behavior Log Messages: /rosout and rqt_console Generating Log Messages: /rosout Logger Levels Reading Log Messages: rqt_console /rosout Versus /rosout_agg Nodes, Topics, and Connections: rqt_graph and rosnode Visualizing the Graph: rqt_graph Problem: Mismatched Topic Names Problem: Mismatched Topic Types and/or Checksums Problem: Incorrect Network Settings Sensor Fusion: rviz Plotting Data: rqt_plot Data Logging and Analysis: rosbag and rqt_bag Logging and Playing Back Data: rosbag Visualizing Bags: rqt_bag Analyzing ROS Bags with Other Tools: rostopic echo -b Summary 22 The ROS Community: Online Resources Etiquette The ROS Wiki ROS Answers Trackers (Bugs and Feature Requests) Mailing Lists and Special Interest Groups Finding and Sharing Code Summary 23 Using C++ in ROS When Should You Use C (or Some Other Language)? Building C++ with catkin package.xml CMakeLists.txt catkin_make Translating from Python to C++ (and Back Again) A Simple Node Topics Services Summary Index ... Programming Robots with ROS Morgan Quigley, Brian Gerkey, and William D Smart Programming Robots with ROS by Morgan Quigley, Brian Gerkey, and William D... This book is meant to be a broad introduction to programming robots with ROS We’ll cover the important aspects of the basic mechanisms and tools that make up the core of ROS and show you how to use them to create software to control your robots. .. and install the ROS packages, and set up the environment and ROS build tools: user@hostname$ sudo sh -c 'echo "deb http://packages .ros. org /ros/ ubuntu trusty main" > /etc/apt/sources.list.d /ros- latest.list'