AntiprotonTechnologies

04Singularity Hub

ROS nodes and topics

ROS (Robot Operating System) is how most research and industry robots are programmed. Its idea is simple: small programs called nodes talk by sending messages on named channels called topics. One node publishes on a topic; any number of nodes can subscribe to it. Like a radio station and its listeners.

Singularity has a built-in message bus that behaves like ROS 2 (and ROS 1), with the same topic names and message types a TurtleBot3 uses. So what you learn here, and most code you write, carries over to a real ROS robot.

The whole picture

Open the Graph tab (under the code) while a program runs to see this drawn live for your own program: every node, every topic, and who talks to whom.

Topics you can read (sensors)

TopicMessage typeHow oftenWhat is in it
/scansensor_msgs/LaserScan10/s360 ranges in meters, index 0 = forward, counter-clockwise; inf = nothing in range
/sonar/frontsensor_msgs/Range20/sone per mount: front, front_left, front_right, left, right, back. Distance in .range (inf = nothing)
/camera/image_rawsensor_msgs/Image15/srgb8 picture, 160 × 120 by default (only while the camera is on)
/line_sensorsstd_msgs/Float32MultiArray50/sIR values left to right, 0 = floor, 1 = tape
/imusensor_msgs/Imu50/sorientation (quaternion), angular_velocity (rad/s), linear_acceleration (m/s²)
/wheel_ticksstd_msgs/Int32MultiArrayevery step[left, right] encoder ticks
/odomnav_msgs/Odometryevery steppose from the wheels (drifts) and twist (speeds)
/gpsgeometry_msgs/PointStamped10/sx, y in meters, with noise
/bumperstd_msgs/Bool20/sTrue while touching something
/ground_truthnav_msgs/Odometryevery stepthe exact pose. Simulator only: use it to check your work, not to drive
/mapnav_msgs/OccupancyGrid~1/sthe SLAM map, 5 cm cells (only while SLAM is on)
/posegeometry_msgs/PoseWithCovarianceStampedwith each scanwhere SLAM thinks the robot is
/goal_posegeometry_msgs/PoseStampedwhen you clickfrom the Map window’s 2D Goal Pose tool

Topics you can publish (to make things happen)

TopicMessage typeWhat happens
/cmd_velgeometry_msgs/TwistDrives the robot: linear.x in m/s (forward +), angular.z in rad/s (left +). Keeps going until the next message
/ledstd_msgs/ColorRGBALED color, r g b from 0 to 1
/headlightsstd_msgs/Float32Headlight brightness, 0 to 1
/camera/panstd_msgs/Float64Camera pan in radians (+ = left), up to ±2.62 (150°)
/camera/tiltstd_msgs/Float64Camera tilt in radians (+ = down), −0.44 to 1.22 (−25° to 70°)
/plan or /pathnav_msgs/PathDrawn as a line in the 3D view: show your planner’s path
/mapnav_msgs/OccupancyGridShown in the Map window: show a map you made
/goal_posegeometry_msgs/PoseStampedSets a goal, as if you had clicked one
any name you likestd_msgs/Float64 (or any number type)Numbers you publish are drawn in the Plot window automatically
the smallest ROS 2 driver
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist

class Driver(Node):
    def __init__(self):
        super().__init__('driver')
        self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
        self.create_timer(0.1, self.tick)      # 10 times a second

    def tick(self):
        msg = Twist()
        msg.linear.x = 0.2                     # forward at 0.2 m/s
        msg.angular.z = 0.5                    # while turning left at 0.5 rad/s: a circle
        self.pub.publish(msg)

rclpy.init()
rclpy.spin(Driver())

The nodes

NodeWhat it is
/singularityThe simulator itself: the robot’s motor driver and every sensor. Subscribes to /cmd_vel, publishes the sensor topics
/slam_toolboxThe SLAM node, while SLAM is on. Subscribes to /scan and /odom, publishes /map and /pose
/robotAppears when you use the simple robot.… commands: they publish on /cmd_vel too
/rviz (Map window)Publishes /goal_pose when you use 2D Goal Pose
/ros2cliThe Terminal, while a ros2 topic pub command runs
your nodesEvery Node you create, with the name you give in super().__init__('name')

Message types and their fields

Type ros2 interface show sensor_msgs/msg/LaserScan in the Terminal to see any message’s fields. The ones you will use most:

MessageFields you will use
geometry_msgs/Twistlinear.x, angular.z
sensor_msgs/LaserScanranges, angle_min, angle_increment, range_min, range_max
sensor_msgs/Rangerange, min_range, max_range, field_of_view
sensor_msgs/Imageheight, width, encoding (rgb8), data (bytes)
sensor_msgs/Imuorientation (x, y, z, w), angular_velocity.z, linear_acceleration
nav_msgs/Odometrypose.pose.position.x/y, pose.pose.orientation, twist.twist.linear.x
nav_msgs/OccupancyGridinfo.width, info.height, info.resolution, info.origin.position, data
nav_msgs/Pathposes: a list of PoseStamped
geometry_msgs/PoseStampedpose.position.x/y, pose.orientation
std_msgs/Bool, Float32, Float64, Int32, Stringdata
std_msgs/Float32MultiArray, Int32MultiArraydata (a list)

Also available: Point, Pose, Pose2D, Quaternion, Vector3, PoseWithCovarianceStamped, TwistStamped, PointStamped, Header, ColorRGBA, Empty, MapMetaData, and the number types Int8 to Int64, UInt8, Float32, Float64. Helpers: from tf_transformations import euler_from_quaternion, quaternion_from_euler.

Terminal commands

The Terminal under the code understands the everyday ros2 commands. Type help to see them. Ctrl + C stops echo, hz and pub; clear clears the screen.

CommandWhat it shows or does
ros2 topic list -tEvery topic and its type
ros2 topic echo /scan --onceOne message from a topic (leave out --once to keep printing; add --full for whole arrays, --field ranges for one field)
ros2 topic hz /imuHow many messages per second
ros2 topic info /scanWho publishes and who subscribes
ros2 topic pub -r 10 /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.2}, angular: {z: 0.5}}"Publish from the keyboard: here, drive in a circle 10 times a second
ros2 node listEvery node
ros2 node info /singularityA node’s topics
ros2 param list / get / setRead and change parameters of a running node
ros2 interface show sensor_msgs/msg/ImuThe fields of a message type
ros2 launch singularity slam.launch.pyStart SLAM
what you see (real output)
$ ros2 topic info /scan
Type: sensor_msgs/msg/LaserScan
Publisher count: 1
  /singularity
Subscription count: 1
  /demo

$ ros2 topic echo /gps --once
header:
  stamp:
    sec: 2
    nanosec: 8333333
  frame_id: 'map'
point:
  x: -1.975828
  y: -2.022083
  z: 0.0
---

Parameters

A parameter is a setting a node reads, which you can change without editing the code. Declare it with self.declare_parameter('kp', 1.0) and read it with self.get_parameter('kp').value. While the program runs, every parameter appears as a slider in the Tune tab. Moving the slider changes it live, and Tune can write the new value back into your code for you.

Some names are filled in from the robot itself, the way a real robot’s launch file would: wheel_radius, wheel_separation, wheel_separation_multiplier, ticks_per_rev and robot_name.

ROS 1 (rospy) side by side

ROS 2 (rclpy)ROS 1 (rospy)
Startrclpy.init(); node = MyNode()rospy.init_node('my_node')
Publisherself.create_publisher(Twist, '/cmd_vel', 10)rospy.Publisher('/cmd_vel', Twist, queue_size=10)
Subscriberself.create_subscription(LaserScan, '/scan', cb, 10)rospy.Subscriber('/scan', LaserScan, cb)
Repeatself.create_timer(0.1, cb)rate = rospy.Rate(10) … rate.sleep()
Logself.get_logger().info('hi')rospy.loginfo('hi')
Parameterself.declare_parameter('kp', 1.0)rospy.get_param('~kp', 1.0)
Runrclpy.spin(node)rospy.spin()

What is the same as real ROS, and what is not

  • The same: topic names, message types and fields, units, the node/publisher/subscriber/timer/parameter code, and the command-line tools for topics, nodes, params and interfaces.
  • Different: Singularity is not a ROS installation. It runs one Python program at a time inside the app; there are no packages, launch files of your own, services, actions or tf. You cannot connect a real ROS computer to it.
  • So on a real robot you will add: a ROS 2 install (Ubuntu), a package for your node, and drivers for your sensors. Page 06 walks through it.

Stuck on something this page did not answer? Write to us at antiprotontechnologies@gmail.com. Paste what you tried and what happened (the Copy details for support button in Singularity’s Help & Support window helps us a lot).