




















Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





















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:
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:
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)
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:
More on these two later in the course)
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.
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
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.
time stamp string frame_id uint8 radiation_type float32 field_of_view float32 min_range float32 max_range float32 range
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')
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:
#!/usr/bin/env python
tutorials to the context
%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.
def process_service_request(req):
res = ConvertMetresToFeetResponse()
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
res.success = True
for test_idx in range(0,10):
rospy.sleep(1)
#Return the response message.
return res
def metres_to_feet_server():
rospy.init_node('metres_to_feet_server', anonymous = False)
service = rospy.Service('metres_to_feet', ConvertMetresToFeet, process_service_request)
rospy.loginfo('Convert metres to feet service is now available.')
rospy.spin()
if name == "main":
metres_to_feet_server()
#!/usr/bin/env python
tutorials to the context
import sys
import rospy
from hrwros_msgs.srv import ConvertMetresToFeet, ConvertMetresToFeetRequest, ConvertMetresToFeetResponse
def metres_to_feet_client(x):
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.
‘rosrun hrwros_week1 metres_to_feet_client.py’.
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
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.