Using ROS

Note

The following examples use the ROS backend. Before running them, please make sure you have the ROS backend correctly configured and the Base system started.

First step

The first step is to connect to ROS to verify that the system is working.

Copy and paste the following example into any Python environment (a standalone script, a CAD environment, etc) and run it, you should see the output Connected: True if everything is working properly:

from compas_fab.backends import RosClient
with RosClient() as client:
    print('Connected: ', client.is_connected)

Yay! Our first connection to ROS!

If you prefer to work without a context manager, the equivalent code is:

from compas_fab.backends import RosClient
client = RosClient()
client.run()
print('Connected: ', client.is_connected)
client.close()

Note

RosClient also supports using callbacks instead of blocking calls.

A callback is a function that is passed to another function as a parameter such that the latter function can call the former at any time during its own execution. Whenever code needs to respond to an event, one of the easiest ways to achieve it is to pass a callback function that the framework will invoke when the event is fired.

Hello World

The Hello world of ROS is to start two nodes: a talker and a listener. The nodes are extremely simple but they exemplify a distributed system with communication between two processes over the ROS infrastructure.

Writing the talker node

The following example starts a ROS node and begins to publish messages in loop (to terminate, press ctrl+c):

import time

from roslibpy import Message
from roslibpy import Topic

from compas_fab.backends import RosClient

with RosClient() as client:
    talker = Topic(client, '/chatter', 'std_msgs/String')

    while client.is_connected:
        talker.publish(Message({'data': 'Hello World!'}))
        print('Sending message...')
        time.sleep(1)

    talker.unadvertise()
Downloads

Writing the listener node

Now let’s move on to the listener side:

import time

from roslibpy import Topic
from compas_fab.backends import RosClient


def receive_message(message):
    print('Heard talking: ' + message['data'])


with RosClient() as client:
    listener = Topic(client, '/chatter', 'std_msgs/String')

    listener.subscribe(receive_message)

    while client.is_connected:
        time.sleep(1)

Running the example

Open a command prompt and start the talker:

python 01_ros_hello_world_talker.py

Now open a second command prompt and start the listener:

python 01_ros_hello_world_listener.py

You should see the listener printing every time it hears the other node talking.

Note

It is not relevant where the files are located. They can be in different folders or even in different computers as long as the ROS master is the same.