Docsity

Robotic Operation System, Manuais, Projetos, Pesquisas de Robótica e Sistemas de Autônomos

Toggle sidebar
bg1
Nodes: These are software processes that do 'stuff' (e.g. process data, command
hardware, execute algorithms). Nodes provide modularity to robotic projects that use ROS.
They are often written in C++ or Python. In this, we will use Python to write them. ROS is
only compatible with Python 2.7.x. Topics: Transport information between nodes, in the
form of messages. In a real robot application you will often have to deal with a large
number of nodes and topics. It is important to know which nodes are talking to each other,
and what topics are being used to pass the information (messages) between nodes.
Don't forget to source your workspace if you want to use ROS commands!
If you've followed the procedure under the Course Setup section correctly, you only need
to execute the following in the shell: $ source $HOME/hrwros_ws/devel/setup.bash
Summary:
There are three main ways to inspect a ROS node:
•Simply list all currently running nodes in the terminal:
rosnode list
•Make a visual graph of all running nodes and their connections:
rqt_graph
•List information about a specific node in the terminal:
rosnode info <node_name>
In the following lectures, we will learn much more about Nodes. For example, we
will see that they can publish (write) to a topic and subscribe (read) from a topic.
ROS topics transport information between nodes. This information is organized as a
data structure and can have different data types. Topics can be identified by their name
and their type. You can think of topics as strongly typed message buses. Any node can
connect to it to send or receive data, as long as they are the right type.
As with nodes, there are three ways to inspect topics:
Don't forget to source your workspace if you want to use ROS commands! If you've
followed the procedure under the Course Standards section correctly, you only need to
execute the following in the shell: $ source $HOME/hrwros_ws/devel/setup.bash
•Display a list of all topics that are currently being exchanged between active
nodes list
•Display information about the data structure of a specific topic
rostopic info <topic_name>
•Print the current content of a topic in the terminal
rostopic echo <topic_name>
Important detail: Do not forget the "/" before node and topic names!
It's time to build your own ROS application structure! There are four fundamental
types of ROS nodes that can be used to build a ROS application:
•Publishers
•Subscribers
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Pré-visualização parcial do texto

Baixe Robotic Operation System e outras Manuais, Projetos, Pesquisas em PDF para Robótica e Sistemas de Autônomos, somente na Docsity!

Nodes: These are software processes that do 'stuff' (e.g. process data, command hardware, execute algorithms). Nodes provide modularity to robotic projects that use ROS. They are often written in C++ or Python. In this, we will use Python to write them. ROS is only compatible with Python 2.7.x. Topics: Transport information between nodes, in the form of messages. In a real robot application you will often have to deal with a large number of nodes and topics. It is important to know which nodes are talking to each other, and what topics are being used to pass the information (messages) between nodes. Don't forget to source your workspace if you want to use ROS commands! If you've followed the procedure under the Course Setup section correctly, you only need to execute the following in the shell: $ source $HOME/hrwros_ws/devel/setup.bash Summary: There are three main ways to inspect a ROS node:

  • Simply list all currently running nodes in the terminal: rosnode list
  • Make a visual graph of all running nodes and their connections: rqt_graph
  • List information about a specific node in the terminal: rosnode info In the following lectures, we will learn much more about Nodes. For example, we will see that they can publish (write) to a topic and subscribe (read) from a topic. ROS topics transport information between nodes. This information is organized as a data structure and can have different data types. Topics can be identified by their name and their type. You can think of topics as strongly typed message buses. Any node can connect to it to send or receive data, as long as they are the right type. As with nodes, there are three ways to inspect topics: Don't forget to source your workspace if you want to use ROS commands! If you've followed the procedure under the Course Standards section correctly, you only need to execute the following in the shell: $ source $HOME/hrwros_ws/devel/setup.bash
  • Display a list of all topics that are currently being exchanged between active nodes list
  • Display information about the data structure of a specific topic rostopic info
  • Print the current content of a topic in the terminal rostopic echo Important detail: Do not forget the "/" before node and topic names! It's time to build your own ROS application structure! There are four fundamental types of ROS nodes that can be used to build a ROS application:
  • Publishers
  • Subscribers
  • Services
  • Actions Please keep in mind, that here we refer to Services and Actions as fundamental types of nodes. That is, we are referring to nodes that use services and actions for communication. Publishers, Subscribers, Services and Actions are used by ROS nodes to communicate between each other.

First, we will focus on Publisher and Subscriber nodes.

Publisher Nodes A ROS node that generates information is called a publisher. A publisher sends information to nodes via topics. With robotics often these publishers are connected with sensors like cameras, encoders, etc. If you use rosnode info you can see to which topics a node is connected, and if these are outbound or inbound connections. Subscriber Nodes A ROS node that receives information is called a subscriber. It's subscribed to information a topic and uses topic callback functions to process the received information. With robotics, subscribers typically monitor system states such as triggering an alert when the robot reaches joint limits. You can again use rosnode info to find information about a subscriber node. Don't forget to source your workspace! PUBLISHER:

Node to publish a string topic.

import rospy from std_msgs.msg import String def simplePublisher(): simple_publisher = rospy.Publisher('topic_1', String, queue_size = 10) rospy.init_node('node_1', anonymous = False) rate = rospy.Rate(10)

The string to be published on the topic.

topic1_content = "my first ROS topic" while not rospy.is_shutdown(): simple_publisher.publish(topic1_content) rate.sleep() if name== 'main': try: simplePublisher() except rospy.ROSInterruptException: pass SUBSCRIBER:

Node to subscribe to a string and print the string on terminal.

More on these two later in the course)

  • scripts/(This folder contains all Python scripts. We will only use Python in this course)
  • src/(This folder contains all C++ source files. We will not use these in this course) To create a new ROS package, we will use catkin: $ cd /src $ catkin_create_pkg hrwros_week2 std_msgs Please keep in mind that you don't need to place the source files of any dependencies, such as std_msgs in the line above. Instead, you can simply install their binaries with the rosdep command: $ install You can also install all ROS package dependencies in one command: $ cd /src $ rosdep install --from-paths. --ignore-src -y src is not the only space in your workspace: there is also the 'devel' space. This contains all binary executables from src. Nodes can process and share information through topics. The information they pass through these topics needs to be structured in some way, to make it actually usable. Such a structure is known as a data structure. In ROS, we can abstract these data structures as ROS message types. Common data structures in ROS are for example floats, integers, and strings. In ROS, we can easily combine multiple data structures using derived message types. For example, to represent a position in 3D space we will need 3 floating point values: X, Y and Z. The derived message type will then be a struct of three floating point numbers: {float x, float y, float z}. These (derived) message types are defined in message files. These message files are typically located in /msg, with the filename .msg. For example, look in the $HOME/hrwros_ws/src/hrwros/hrwros_msgs/msg folder for some examples. Example: Ultrasound distance sensor. We want to construct a new message type SensorInformation It should contain:
  • message type for interfacing with distance sensors
  • A string containing the manufacturer name
  • An unsigned integer containing the sensor part number We would create the following file: $HOME/hrwros_ws/src/hrwros/hrwros_msgs/msg/SensorInformation.msg. It will contain the following: sensor_msgs/Range sensor_data

string maker_name uint32 part_number We can see something really interesting here: We use an already derived message, sensor_msgs/Range, and simply add a string and an integer to it. So we can create new message types using already existing derived message types! This idea of stacking is really useful in ROS, since you can easily re-use what already exists. So in the above example, the sensor_msgs/Range already contains everything we need from the range sensor itself, and we only add the maker name and the part number.

1. Publisher, Subscriber and Custom Message Type: THE PROCESS

Ok, we have ROS nodes in a ROS application. And n odes process information. And the information is organized as data structures. These data structures are called ROS message types. And, nodes use topics to talk to each other and exchange information. Therefore, topic type is just an abstract concept. A topic just carries whatever information the nodes want a topic to carry. So, if the same nodes exchange a different kind of information, the topic can carry that information. In essence, topic types are just abstract concepts and they acquire or inherit the ROS message type that they are asked to carry by the ROS nodes. 1.1. CREATING A NEW MESSAGE TYPE

  1. Using ‘ roscd ’ to acess workspace msg;
  2. Then we go to the msg folder with ‘ cd msg’ or mkdir msg;
  3. Inside /msg create message file, like: SensorInformation.msg with ‘ touch SensorInformation.msg’;
  4. With ‘ rosmsg show /’ can visualize all message types direct linked with the tapped , like: ‘ rosmsg show sensor_msgs/’ Obs. If you use any type of predefined msg from ROS, is know that you should keep the message template open for your guide in msg constructing;
  5. After all, define the message construct. Inside SensorInformation.msg folder, like: Format → Variable type , like String, uint32, ROS type, etc. And Variable name. Formate a pair: [Variable Type, Variable Name ]. So, SensorInformation.msg looks like: { sensor_msgs/Range sensor_data ; string maker_name ; uint32 part_number };
  6. Add the new message type ‘SensorInformation.msg’ inside CmakeList.txt in the ‘ add_message_files() ’ function;
  • sensor_info.sensor_data.min_range = 0.
  • sensor_info.sensor_data.max_range = 2.
  • Fill in manufacture name and part number

  • sensor_info.maker_name = ‘The ultrasound company’
  • sensor_info.part_number = ‘123456’
  • while not rospy.is_shutdown():
  • Infinite loop for refeed the values

  • sensor_info.sensor_data.range = getSensorData( sensor_info.sensor_data.radiation_type, sensor_info.sensor_data.min_range, sensor_info.sensor_data.max_range )
  • Publish the sensor information on the /sensor_info topic

  • si_publisher.publish(sensor_info)
  • rate.sleep()
  • if name== 'main':
  • try:
  • sensorInfoPublisher()
  • except rospy.ROSInterruptException: pass

5. The ‘ rospy.Publisher() ’ function receive two main arguments:

Topic Name and Message Type, like: rospy.Publisher(TopicName, MessageType, queue = 10). So, rospy.Publisher(sensor_info, SensorInformation, queue = 10). It mean that this script create a new topic called ‘sensor_info’ that can be published (writable) with message in SensorInformation types.

  1. The ‘rospy.init_node()’ function receive one main argumet: Node name. Like: rospy.init_node(NodeName, anonymous = False). So, rospy.init_node(sensor_info_publisher, anonymous = False). It mean that this script define a new name for this specific node called ‘sensor_info_publisher’ that can be discovery for anyother nodes, with no-anonymous mode.
  2. Create a new Object that reference for new message type, so: The topic ‘ sensor_info ’ has a message type ‘ SensorInformation ’ → sensor_info = SensorInformation(). According of message type SensorInformation is necessary populate the specfic field of respective data information. The type of ‘ SensorInformation ’ is:
    1. sensor_msgs/Range sensor_data uint8 ULTRASOUND= uint8 INFRARED= std_msgs/Header header uint32 seq

time stamp string frame_id uint8 radiation_type float32 field_of_view float32 min_range float32 max_range float32 range

  1. string maker_name
  2. uint32 part_number What its mean? So, sensor_data is an Object with sensor_msgs/ Range type. And it have that structure:
  3. sensor_data = {
  4. ULTRASOUND,
  5. INFRARED,
  6. header = {
  7. seq,
  8. stamp,
  9. frame_id
  10. },
  11. radiation_type,
  12. field_of_view,
  13. min_range,
  14. max_range,
  15. range
  16. },
  17. maker_name,
  18. part_number And each proprierty of that object can be acessed by: sensor_info. sensor_data . , like: sensor_info. sensor_data .min_range or sensor_info. sensor_data .header.stamp;
  19. Make the infinite call of the refeed function: getSensorData();
  20. And, alfter all initialize the sensorInfoPublisher().
  21. Starting the system: ‘ ros core ’, in new terminal: ‘ ros run hrwros_week1 sensor_info_publisher.py’ [ rosrun will locate PACKAGE

Now Fill in the sensor data information. There you can determine the minimum and maximum range of the sensor. sensor_info.sensor_data.radiation_type = sensor_info.sensor_data.ULTRASOUND Fill in the manufacturer name and part number. sensor_info.maker_name = 'The Ultrasound Company' sensor_info.part_number = 123456 Sensor data needs to be updated frequently. Therefore a loop is necessary. sensor_info.sensor_data.range = getSensorData Publish the updated sensor data on this sensor_infor topic. si_publisher.publish(sensor_info) Let's call the correct function in the if loop. sensorInfoPublisher() Starting your new ROS node roscore a CCS after sourcing the setup files. Then, in another CCS, the ROS node with the following command, after sourcing the setup files: $rosrun hrwros_week1 sensor_info_publisher.py This will lead to an executable error. This error can be resolved by a simple command which makes the node executable. $ roscd hrwros_week1/scripts $ chmod +x sensor_info_publisher.py Try running the ROS node with the previous command. This will lead to an import error. This is due to an incorrect message definition. We can change this with the gedit editor. $ gedit sensor_info_publisher.py There we need to change std_msgs.msg to hrwros_msgs.msg. Try to run the node again. Which leads to a third error, the getSensorData function is not known. For that reason, we always need to tell python where we got functions which means it is necessary to import the utilities. So we add the following with the gedit editor in sensor_info_publisher.py. from hrwros_utilities.sim_sensor_data import distSensorData as getSensorData Now you can run the ROS node without errors. Inspecting our node This node is a publisher, publishing to a topic. So let's see if we can find the topic. $ rostopic list (we look for/sensor_info topic) Let's look at its contents. $ rostopic echo /sensor_info It's always nice to receive some acknowledgement that a ROS node is working. To do that we open our node in the gedit editor. $ gedit sensor_info_publisher.py

After publishing our topic we print a log message by adding the following linen of code to the file: rospy.loginfo('All went well. Publishing topic')

1.3. CREATING A SUBSCRIBER NODE WITH A CUSTOM

MESSAGE TYPE

  1. Using ‘roscd __ ’ to acess workspace that contain scripts folder;
  2. The files looks like: CMList.txt, launch, package.xml, scripts;
  3. Inside /script create the publisher node file, with ‘ touch sensor_info_subscriber.py’;
  4. Then, use the previous Publisher template for copy this inside of new sensor_info_subscriber, like: ‘cp template_subscriber_script.py sensor_info_subscriber.py’;
  • Node to subscribe to sensor information topic and print distance data.

  • import rospy
  • from hrwros_msgs.msg import SensorInformation
  • Topic callback function.

  • def sensorInfoCallback(data):
  • rospy.loginfo(' Distance reading from the sensor is: %f', data.sensor_data.range)
  • def sensorInfoListener():
  • rospy.init_node('sensor_info_subscriber’ , anonymous = False)
  • rospy.Subscriber('sensor_info' , SensorInformation, sensorInfoCallback)
  • spin() simply keeps python from exiting until this node is stopped

  • rospy.spin()
  • if name == 'main':
  • sensorInfoListener()

So, REMAINDER →

Start a new CCS and source the workspace setup files.

Use the template and start editing it. We will first create a new file, and copy the contents of the example file into it. $ roscd hrwros_week1/scripts $ touch sensor_info_subscriber.py $ cp template_subscriber_script.py sensor_info_subscriber.py

measurement in metres, and the response would contain the measurement in imperial feet plus a boolean value indicating the conversion was successful. We would create the file hrwros_msgs/srv/ConvertMetresToFeet.srv:

  1. Using ‘ roscd ’ to acess workspace services;
  2. Then we go to the ‘srv’ folder with ‘ cd srv’ or mkdir srv;
  3. Inside /srv create service file, like: ConvertMetresToFeet.srv with ‘ touch ConvertMetresToFeet.srv’;
  4. Inside ‘CovertMetresToFeet.srv’:
  • float64 measurement_metres # Request field
  • --- # Demarcation between request and response
  • float64 measurement_feet # Response field
  • bool succes
  1. Add the new service ‘CovertMetresToFeet.srv’ inside CmakeList.txt in the ‘ add_service_files() ’ function;
  2. Inside the Workspace (We call it hrwros_ws ):
    1. Path: hrwros_ws / src / hrwros / hrwros_msgs
    2. Folders inside Hrwros_msgs: msg, srv, CmakeList.txt, package.xml.
    3. And, at least, make catkin build command, wich creates a importable python objects for the new message type.
    4. So, for check if all be done verify if the services escope has been defined. With: ‘ rossrv show hrwros_msgs/ConvertMetresToFeet’
  3. Create a Client-Server Scripts: 1. Server:
  • #!/usr/bin/env python

  • This code has been adapted from the ROS Wiki ROS Service

    tutorials to the context

  • of this course.

  • (http://wiki.ros.org/ROS/Tutorials/WritingServiceClient

    %28python%29)

  • from hrwros_msgs.srv import ConvertMetresToFeet, ConvertMetresToFeetRequest, ConvertMetresToFeetResponse

  • import rospy

  • import numpy as np

  • _CONVERSION_FACTOR_METRES_TO_FEET = 3.28 # Metres -> Feet conversion factor.

  • Service callback function.

  • def process_service_request(req):

  • Instantiate the response message object.

  • res = ConvertMetresToFeetResponse()

  • Perform sanity check. Allow only positive real numbers.

  • Compose the response message accordingly.

  • if(req.distance_metres < 0):

  • res.success = False

  • res.distance_feet = -np.Inf # Default error value.

  • else:

  • res.distance_feet = _CONVERSION_FACTOR_METRES_TO_FEET

    • req.distance_metres
  • res.success = True

  • for test_idx in range(0,10):

  • rospy.sleep(1)

  • #Return the response message.

  • return res

  • def metres_to_feet_server():

  • ROS node for the service server.

  • rospy.init_node('metres_to_feet_server', anonymous = False)

  • Create a ROS service type.

  • service = rospy.Service('metres_to_feet', ConvertMetresToFeet, process_service_request)

  • Log message about service availability.

  • rospy.loginfo('Convert metres to feet service is now available.')

  • rospy.spin()

  • if name == "main":

  • metres_to_feet_server()

    1. Client: #!/usr/bin/env python
  • #!/usr/bin/env python

  • This code has been adapted from the ROS Wiki ROS Service

    tutorials to the context

  • of this course.

  • import sys

  • import rospy

  • from hrwros_msgs.srv import ConvertMetresToFeet, ConvertMetresToFeetRequest, ConvertMetresToFeetResponse

  • def metres_to_feet_client(x):

  • First wait for the service to become available.

  • rospy.loginfo("Waiting for service...")

  • rospy.wait_for_service('metres_to_feet')

$ mkdir srv $ cd srv $ touch ConvertMetresToFeet.srv Now our service file is created, we can start editing it. Remember, we first want the request message type, then a demarcation of three dashes, and then a response message type: float64 distance_metres # Request message: Distance in (m) to be converted to (ft) --- # Demarcation float64 distance_feet # Response message: Distance in (ft) after conversion b ool success # Response message: Success or failure of conversion Now, just like we did for messages, we add our new service to the CMakeLists.txt file in the hrwros_msgs/ folder. Note that services have their own section, after messages. Add the name of our new service definition file after the FILES entry. Don't forget the .srv file extension. Finish by building our service by running the catkin b command. We can check if it worked correctly by using the rossrv command: $ rossrv show hrwros_msgs/ConvertMetresToFeet $ rossrv show hrwros_msgs/ConvertMetresToFeet -r The terminal should show the request message field, and the response message field. Inspecting our service server code: Now we've created a new service, we can use it in our code. Let's go to the week 1 script folder, where we already have two template implementations. Let's begin by inspecting the server: metres_to_feet_server.py. We are importing the newly created service definitions from hrwros_msgs.srv. Note that we not only have to import the service definition, but also explicitly the request and response message definitions. The service request is processed in the service callback function.

  • We first create an object for the response message type, and in the example, do a check in the distance input to check if it is a positive real number.
  • If the sanity check fails, we return a default error value in the response.
  • Otherwise, we do the conversion and return both the converted value and a flag that indicates the conversion was successful.
  • In either case, we return the response. Then, we have the next function for the administrative settings of the service server node.
  • Here, we create a ROS node for our service.
  • We create the actual service by giving it a name, a type, and a callback function for processing a service request.
  • Finally, in the main function we start the service server node. Inspecting our service client code We will now be looking at the service client example: metres_to_feet_client.py. Lines 6 through 8 contain all the required imports, and the client definition on. We first wait for the required service to become available. Then, we create a service proxy to be able to call the service. Then, we actually call the service on , and return the service response from the service call. In the main function, we have the ROS node for the service client. We send a test value to the server via the client. Once we have a response, we check if the conversion was successful, and report the return value accordingly. We are using the logerr function for error messages. Using the service server & client First, make sure you are in the hrwros_msgs folder. Start roscore in a separate terminal. Then, source our setup files and run our server, and: $ $HOME/hrwros_ws/devel/setup.bash $ rosrun hrwros_week1 metres_to_feet_server.py The service is now available. Time to also start the ROS client in a separate terminal: $HOME/hrwros_ws/devel/setup.bash $ rosrun hrwros_week1 metres_to_feet_client.py The terminal will both display the request and response messages. We learned, that services will block execution. Let's look at that as well. Since the processing, which is blocking, is happening in the server, let's go to the server file and add a delaying test loop. In metres_to_feet_server.py, navigate to #L27 and add the followingblock of code: for test_idx in range(0,10): rospy.sleep(1) On the client side, let's write a log message after the response has been received. In metres_to_feet_client.py, navigate to #L21 and add the following block of code: print('I only got here AFTER the service call was completed!') First, terminate the server in the terminal (CTRL+C), and restart it. Restart the client the same way. You will now see the client will only print out every 10 seconds, because the processing is not complete yet on the server side.

To test: 1. ‘roscore’; 2. ‘rosrun hrwros_week1 metres_to_feet_server.py’; 3.

‘rosrun hrwros_week1 metres_to_feet_client.py’.

  • Additional actions which are used internally by the actionlib package:
  1. CounterWithDelayActionFeedback
  2. CounterWithDelayActionGoal
  3. CounterWithDelayAction
  4. CounterWithDelayActionResult CounterWithDelayAction.msg is an aggregation of the other action messages. This is the action type of our action client. The action client code is something that we as users develop to leverage the facilities of the actionlib ROS package. Sent goals are registered by the action server and the actionlib package. The package requires additional information which is CounterWithDelayAction.msg. contains:
  1. Timestamp and header info;
  2. Unique goal identifier;
  3. Goal message. Action Result contains:
  4. Timestamp and header info;
  5. Different states the goal can be in; Feedback contains:
  6. Timestamp and header info;
  7. Different states the goal can be in;
  8. Feedback message. Action server topics
  • Feedback topic is published by the action server an has action feedback message type;
  • Action server subscribers to the cancel topic and is of the GoalID type. Attention!
  • Simple Action Server/Client.
  • Non-blocking execution of ONE goal at a time.
  • New goal to the same action server will pre-empt an active goal. Meaning that the active goal is completed first before a new goal will be processed.
  • n action file Let's first create our action folder and our new action file. $ mkdir action $ cd action $ nano CounterWithDelay.action

We first define the goal message as the number of counts to count up to. Then a result message which is a message for the result and a feedback message to indicate the numbers of counts elapsed. uint32 num_counts

string result_message

uint32 counts_elapsed Now we update the CMakeLists.txt file with the vim editor in the action files subsection. CounterWithDelay.action We need to add the actionlib package that provides all the ROS action functionalities. Weneed to add it at all dependancy locations. actionlib actionlib_mgs Update the package.xml file also with the dependency. (#L21) Now run catkin build or in short catkin b. Action message Don't forget to source your ROS workspace first! $ source $HOME/hrwros_ws/devel/setup.bash If we type the complete action $ rosmsg showhrwros_msgs/CounterWithDelayAction will see the complete message definition. We need to pay attention to where our message definitions are located as a lot of the message is for the package. If you want to see the message definition, you can go to the hrwros_msgs package folder. $ roscd hrwros_msgs And run the following script. $ rosrun actionlib_msgs genaction.py -o msg action/CounterWithDelay.action There we find all the action definitions. $ rosmsg show hrwros_msgs/ Similar to the services in the previous module we have the action server and the action client. This example script has been modified from the tutorial on the ROS wiki to suit this course context. The relevant imports and the python class implementation of the action server.