Introduction To ROS Programming For Robotics - ETH Z

Transcription

Programming for RoboticsIntroduction to ROSCourse 4Tom Lankhorst, Edo JelavicProf. Dr. Marco HutterTom Lankhorst 01.03.2021 1

Course StructureCourse 1Course 2Course 3Course 4Deadline for Ex. 1.Deadline for Ex. 2.Deadline for Ex. 3.Multiple Choice TestLecture 1Lecture 2Exercise 1 Intro.Course 5Exercise 2 Intro.Lecture 3Lecture 4BreakExercise 3 Intro.Exercise 4 Intro.Case StudyExercise 5 Intro.Exercise 1Exercise 2Exercise 3Exercise 4Exercise 5Deadline for Ex. 5.Tom Lankhorst 01.03.2021 2

Evaluation – Multiple Choice Test The test counts for 50 % of the final grade The multiple choice test ( 40 min) takes place at the last course day:05.03.2021 at 08:00 (sharp, not 08:15), HG E3Tom Lankhorst 01.03.2021 3

Ex 4 grading session Moved to Thursday04.03.2021 at 08:00 (sharp, not 08:15)Tom Lankhorst 01.03.2021 4

Overview Course 4 ROS servicesROS actions (actionlib)ROS timeROS bagsDebugging strategies Intro to ROS 2 conceptsTom Lankhorst 01.03.2021 5

ROS Services Request/response communication betweennodes is realized with services The service server advertises the service The service client accesses this serviceService Client Similar in structure to messages, servicesare defined in *.srv filesList available services with rosservice listShow the type of a serviceRequestNode 1RequestResponse*.srvResponseservicenameNode 2Service ServerRequestResponseService definitionRequest--Response rosservice type /service nameCall a service with the request contents, autocomplete with tab rosservice call /service name argsMore infowiki.ros.org/ServicesTom Lankhorst 01.03.2021 6

ROS ServicesExamplesstd srvs/Trigger.srv--bool successstring messageRequestResponsenav msgs/GetPlan.srvgeometry msgs/PoseStamped startgeometry msgs/PoseStamped goalfloat32 tolerance--nav msgs/Path planTom Lankhorst 01.03.2021 7

ROS Service ExampleStarting a roscore and aadd two ints server nodeIn console nr. 1:Start a roscore with roscore roscore.SUMMARY PARAMETERS* /rosdistro: noetic* /rosversion: 1.15.9NODESauto-starting new masterprocess[master]: started with pid [35]ROS MASTER URI http://501c634e6a82:11311/setting /run id ut-1]: started with pid [45]started core service [/rosout]In console nr. 2:Run a service demo node with rosrun roscpp tutorials add two ints server rosrun roscpp tutorials add two ints serverTom Lankhorst 01.03.2021 8

ROS Service ExampleConsole Nr. 3 – Analyze and call serviceSee the available services with rosservice listSee the type of the service with rosservice type /add two ints rosservice list/add two ints/add two ints server/get loggers/add two ints server/set logger level/rosout/get loggers/rosout/set logger level rosservice type /add two intsroscpp tutorials/TwoInts rossrv show roscpp tutorials/TwoIntsint64 aint64 b--int64 sumtabShow the service definition with rossrv show roscpp tutorials/TwoIntsCall the service (use Tab for auto-complete) rosservice call /add two ints "a: 10b: 5" rosservice call /add two ints "a: 10b: 5"sum: 15 rosrun roscpp tutorials add two ints server[ INFO] [1614524882.675833648]: request: x 10, y 5[ INFO] [1614524882.676700815]:sending backresponse: [15]Tom Lankhorst 01.03.2021 9

ROS C Client Library (roscpp)Service Server Create a service server withros::ServiceServer service nodeHandle.advertiseService(service name,callback function); When a service request is received,the callback function is called with therequest as argument Fill in the response to the responseargument Return to function with true to indicate that ithas been executed properlyMore infowiki.ros.org/roscpp/Overview/Servicesadd two ints server.cpp (use OO-approach in exercises)#include ros/ros.h #include roscpp tutorials/TwoInts.h bool add(roscpp tutorials::TwoInts::Request &request,roscpp tutorials::TwoInts::Response &response){response.sum request.a request.b;ROS INFO("request: x %ld, y %ld", (long int)request.a,(long int)request.b);ROS INFO(" sending back response: [%ld]",(long int)response.sum);return true;}int main(int argc, char **argv){ros::init(argc, argv, "add two ints server");ros::NodeHandle nh;ros::ServiceServer service nh.advertiseService("add two ints", add);ros::spin();return 0;}Tom Lankhorst 01.03.2021 10

ROS C Client Library (roscpp)Service Client Create a service client withros::ServiceClient client nodeHandle.serviceClient service type (service name); Create service request contentsservice.request Call service withadd two ints client.cpp#include ros/ros.h #include roscpp tutorials/TwoInts.h #include cstdlib int main(int argc, char **argv) {ros::init(argc, argv, "add two ints client");if (argc ! 3) {ROS INFO("usage: add two ints client X Y");return 1;}ros::NodeHandle nh;ros::ServiceClient client nh.serviceClient roscpp tutorials::TwoInts ("add two ints");roscpp tutorials::TwoInts service;service.request.a atoi(argv[1]);service.request.b atoi(argv[2]);if (client.call(service)) {ROS INFO("Sum: %ld", (long int)service.response.sum);} else {ROS ERROR("Failed to call service add two ints");return 1;}return 0;client.call(service); Response is stored in service.responseMore infowiki.ros.org/roscpp/Overview/Services}Tom Lankhorst 01.03.2021 11

ROS C Client Library (roscpp)Service Client rosrun roscpp tutorials add two ints client 10 20[ INFO] [1614529295.123646417]: Sum: 30Tom Lankhorst 01.03.2021 12

ROS Actions (actionlib)Action Similar to service calls, but provide possibility to Cancel the task (preempt) Receive feedback on the progress Best way to implement interfaces totime-extended, goal-oriented behaviors Similar in structure to services, action aredefined in *.action files Internally, actions are implemented with a set oftopicsGoalCancelNode 1Action Client*.actionStatusFeedbackResultNode 2Action ServerAction definitionGoal--Result--FeedbackMore etailedDescriptionTom Lankhorst 01.03.2021 13

ROS Actions (actionlib)Averaging.actionint32 samples--float32 meanfloat32 std dev--int32 samplefloat32 datafloat32 meanfloat32 std devFollowPath.actionGoalResultFeedbacknavigation msgs/Path path--bool success--float32 remaining distancefloat32 initial distanceTom Lankhorst 01.03.2021 14

ROS Parameters, Dynamic Reconfigure, Topics, Services, andActions esActionsDescriptionGlobal constantparametersLocal, changeableparametersContinuous datastreamsBlocking call forprocessing a requestNon-blocking,preemptable goaloriented tasksApplicationConstant settingsTuning parametersOne-way continuousdata flowShort triggers orcalculationsTask executions androbot actionsExamplesTopic names, camerasettings, calibrationdata, robot setupController parametersSensor data, robotstateTrigger change,request state,compute quantityNavigation, grasping,motion executionTom Lankhorst 01.03.2021 15

ROS Time Normally, ROS uses the PC’s system clockas time source (wall time) For simulations or playback of logged data, itis convenient to work with a simulated time(pause, slow-down etc.) To work with a simulated clock: To take advantage of the simulated time, youshould always use the ROS Time APIs: ros::Timeros::Time begin ros::Time::now();double secs begin.toSec(); ros::Duration Set the /use sim time parameterros::Duration duration(0.5); // 0.5sros::Duration passed ros::Time()::now()- begin; rosparam set use sim time true Publish the time on the topic /clock from ros::Rate Gazebo (enabled by default) ROS bag (use option --clock)More /Timeros::Rate rate(10); // 10Hz If wall time is required, useros::WallTime, ros::WallDuration,and ros::WallRateTom Lankhorst 01.03.2021 16

ROS Bags A bag is a format for storing message data Binary format with file extension *.bag Suited for logging and recording datasets forlater visualization and analysisRecord all topics in a bag rosbag record --allRecord given topics rosbag record topic 1 topic 2 topic 3Stop recording with Ctrl CBags are saved with start date and time as filename in the current folder (e.g.2019-02-07-01-27-13.bag)Show information about a bag rosbag info bag name.bagRead a bag and publish its contents rosbag play bag name.bagPlayback options can be defined e.g. rosbag play --rate 0.5 bag name.bag--rate factorPublish rate factor--clockPublish the clock time (setparam use sim time to true)--loopLoop playbacketc.More infowiki.ros.org/rosbag/CommandlineTom Lankhorst 01.03.2021 17

Debugging StrategiesDebug with the tools you have learnedLearn new tools Compile and run code often to catch bugs early Understand compilation and runtime error messages Use analysis tools to check data flow (rosnodeinfo, rostopic echo, roswtf, rqt graph etc.) Visualize and plot data (RViz, RQT Multiplot etc.) Divide program into smaller steps and checkintermediate results (ROS INFO, ROS DEBUG etc.) Make your code robust with argument and returnvalue checks and catch exceptions Extend and optimize only once a basic version works If things don’t make sense, clean your workspace catkin clean --allBuild in debug mode and use GDB or Valgrind catkin config --cmake-args-DCMAKE BUILD TYPE Debug catkin config --cmake-args-DCMAKE BUILD TYPE Release Use debugger breakpoints, e.g. in Eclipse Write unit tests and integration tests to discoverregressionsMore oslaunch%20Nodes%20in%20Valgrind%20or%20GDBTom Lankhorst 01.03.2021 18

Unit Tests, Integration Tests, Automatic TestingAn investment in the quality of your code Unit tests feed a known input to, and expect a knownoutput of your codeMapping UnitTestControl Unit TestMappingAlgorithmControlAlgorithmTests the interface of your code Forces you to reason about its contract Leads to better designed code Integrations tests check the functionality andbehaviour of your program Automated tests reduce the risk of bugs, andregressionsRobot Locomotion Integration TestMappingAlgorithmControlAlgorithmTom Lankhorst 01.03.2021 19

Setting Up up a Developer’s PCTom Lankhorst 01.03.2021 20

Further References ROS Wiki http://wiki.ros.org/ Installation http://wiki.ros.org/ROS/Installation Tutorials http://wiki.ros.org/ROS/Tutorials Available packages http://www.ros.org/browse/ ROS Cheat Sheet ing-system-cheat-sheet/ https://kapeli.com/cheat ex ROS Best Practices https://github.com/leggedrobotics/ros best practices/wiki ROS Package Template https://github.com/leggedrobotics/ros bestpractices/tree/master/ros package templateTom Lankhorst 01.03.2021 21

Contact InformationETH ZurichRobotic Systems LabProf. Dr. Marco HutterLEE H 303Leonhardstrasse 218092 ZurichSwitzerlandLecturersTom Lankhorst (tom.lankhorst@mavt.ethz.ch)Edo Jelavic (edo.jelavic@mavt.ethz.ch)Course s.htmlrsl.ethz.chTom Lankhorst 01.03.2021 22

ROS 2 We will give a brief intro and point you to some resources There is still a lot of ROS 1 code out there ROS 2 intro PhilosophyDifferencesCommands like toolsLaunch filesROS bridgeEdo Jelavic 01.03.2021 23

Why ROS 2? ROS 1 was not designed with all of today’s use cases in mindDesigned mainly for researchInitially only designed for PR2Never really designed for Real-timeMore infohttps://design.ros2.org/articles/why ros2.htmlEdo Jelavic 01.03.2021 24

Why ROS 2? - new use cases Teams of robotsNot suited for bare-metal types of micro controlledNon real time communicationLossy networksUses in research & industry (e.g. certification)API redesignMore infohttps://design.ros2.org/articles/why ros2.htmlEdo Jelavic 01.03.2021 25

Difference between ROS 1 and ROS 2 Support for other OS’sat least C 11 and Python 3 (C 03 before Noetic and Python 2 in ROS 1)Using off the shelf middleware (as opposed to custom)Tighter Python integration (e.g. launch files are in Python)Real time nodes (with some assumptions though)etc Technical changes under the hood, fewer conceptual changesMore do Jelavic 01.03.2021 26

ROS 2 concepts Graph Concepts (similar to ROS 1) nodes, messages, topics Nodes (similar to ROS 1) ROS Client library (RCL) rclcpp - C rclpy - Python Discovery similar to ROS 1 However nodes establish contacts only if they have compatible Qualityof service settingsMore do Jelavic 01.03.2021 27

Nodes Run a node withros2 run package name executable name List all nodes withros2 node list Retrieve information about a node withros2 node info node name More standing-ROS2-Nodes/Edo Jelavic 01.03.2021 28

Where is the rosmaster? ROS1 - master-follower architecture ROS2 - replaced by Data Distribution Service (DDS) DDS is a distributed service that does the discovery,marshalling and transport in the backgroundMore org/articles/ros on dds.htmlEdo Jelavic 01.03.2021 29

ROS 2 messages The messages stay same as in ROS 1 .msg and .srv files are converted into .idl files andinterfaces are created (same as ROS 1) You have to create them using CMakeLists.txtfind package(rosidl default generatorsREQUIRED)rosidl generate interfaces( {PROJECT NAME}"msg/Num.msg""srv/AddThreeInts.srv")More mROS2-Interfaces/Edo Jelavic 01.03.2021 30

ROS 2 messagesEdo Jelavic 01.03.2021 31

ROS 2 Workspace Environment Defines context for the current workspace, same as ROS 1 Default workspace loaded with source /opt/ros/foxy/setup.bash You can overlay your workspaces, same as in ROS 1You can overlay multiple workspaces and more than one ROS 2distribution installedCheck your ROS2 configuration:printenv grep ROSMore guring-ROS2-Environment/Edo Jelavic 01.03.2021 32

Building packages in ROS 2 catkin build used in ROS1 is replaced by the colcon build tool Clone a package: git clone https://github.com/ros/ros tutorials.git -b foxy-devel Build from the top level folder (where src is) with: colcon build You still need to source your workspace source install/setup.bash - source workspace and underlay source install/local setup.bash - sources only the workspaceMore n-Tutorial/Edo Jelavic 01.03.2021 33

Creating packages in ROS 2 You can start by creating a package ros2 pkg create --build-type ament cmake package name In addition the ros2 can also create a node for you ros2 pkg create --build-type ament cmake --node-name node name package name You can also list all the dependencies ros2 pkg create pkg-name --dependencies [deps]More n-Tutorial/Edo Jelavic 01.03.2021 34

Launching multiple nodes in ROS 2 No more xml launch files Launch files are written in Python You can launch a file with: ros2 launch pkg name launch file name If you are writing a C package, you need to ensure that launchfiles are copied over # Install launch files.install(DIRECTORYlaunchDESTINATION share/ {PROJECT NAME}/)More n-Tutorial/Edo Jelavic 01.03.2021 35

Can you use both ROS1 and ROS2? Yes, there is a bridge that will pass messages from both sides You need to (in the following order): source ROS1source ROS2export ROS MASTER URIrun the bridge with: ros2 run ros1 bridge dynamic bridge The bridge should be running in the backgroundMore infohttps://index.ros.org/p/ros1 bridge/github-ros2-ros1 bridge/Edo Jelavic 01.03.2021 36

Summary of ROS2 vs ROS1ROSROS 2Uses TCPROS (custom version of TCP/IP) communication protocolUses DDS (Data Distribution System) for communicationUses ROS Master for centralized discovery and registration. Completecommunication pipeline is prone to failure if the master failsUses DDS distributed discovery mechanism. ROS 2 provides a custom API toget all the information about nodes and topicsROS is only functional on Ubuntu OScompatible with Ubuntu, Windows 10 and OS XUses C 03 and Python2 before NoeticUses C 11 (potentially upgradeable) and Python3ROS only uses CMake build systemROS 2 provides options to use other build systemsHas a combined build for multiple packages invoked using a singleCMakeLists.txtSupports isolated independent builds for packages to better handleinter-package dependenciesData Types in message files do not support default valuesData types in message files can now have default values upon initializationroslaunch files are written in XML with limited capabilitiesroslaunch files are written in Python to support more configurable andconditioned executionCannot support real-time behavior deterministically even with real-time OSSupports real-time response with apt RTOS like tedEdo Jelavic 01.03.2021 37

ROS 2 resourcesAwesome ROS on nt/#rosconROS2 package templatehttps://github.com/leggedrobotics/ros best practices/tree/foxy(package template is still work in progress)ROS Indexhttps://index.ros.org/doc/ros2/Edo Jelavic 01.03.2021 38

Programming for Robotics Introduction to ROS Tom Lankhorst 01.03.2021. Tom Lankhorst 2 Course Structure Lecture 1 Exercise 1 Intro. Exercise 1 Course 1 Lecture 2 Deadline for Ex. 1. Exercise 2 . ROS Parameters, Dynamic Reconfigure, Topics, Services, and Actions Comparison 01.03.2021 Parameters Dynamic Reconfigure