LCM
Python Tutorial

Sending and receiving LCM messages with Python

Introduction

This tutorial will walk you through the main tasks for exchanging LCM messages using the Python API. The topics covered in this tutorial are:

This tutorial uses the example_t message type defined in the type definition tutorial, and assumes that you have generated the Python bindings for the example type by running

1 lcm-gen -p example_t.lcm

After running this command, you should have the following files:

1 exlcm/example_t.py
2 exlcm/__init__.py

The first file contains the Python bindings for the example_t message type, and the init.py file sets up a Python package. If you have the time, take a moment to open up the files and inspect the generated code. Note that if exlcm/__init__.py already existed, then it will be appended to if necessary, and the existing contents left otherwise untouched.

Initializing LCM

The first task for any application that uses LCM is to initialize the library. In Python, this is very straightforward:

1 import lcm
2 
3 lc = lcm.LCM()

The primary communications functionality is contained in the lcm.LCM class. The constructor initializes communications resources, and has a single optional argument. If no argument is given, as above, then the LCM instance is initialized to reasonable defaults, which are suitable for communicating with other LCM applications on the local computer. The argument can also be a string specifying the underlying communications mechanisms. The LCM Python class itself is a wrapper around the C LCM library, so for information on setting the class up for communication across computers, or other usages such as reading data from an LCM logfile (e.g., to post-process or analyze previously collected data), see the documentation for lcm_create().

If an error occurs initializing LCM, then an IOError is raised.

Publishing a message

When you create an LCM data type and generate Python code with lcm-gen, that data type will then be available as a Python class with the same name. For example_t, the Python class that gets generated looks like this:

1 class example_t(object):
2  def __init__(self):
3  self.timestamp = 0
4  self.position = [ 0.0 for dim0 in range(3) ]
5  self.orientation = [ 0.0 for dim0 in range(4) ]
6  self.num_ranges = 0
7  self.ranges = []
8  self.name = ""
9  self.enabled = False

Notice here that fixed-length arrays in LCM appear as Python lists initialized to the appropriate length, and variable length arrays start off as empty lists. All other fields are initialized to some reasonable defaults.

We can instantiate and then publish some sample data as follows:

1 import lcm
2 from exlcm import example_t
3 
4 msg = example_t()
5 msg.timestamp = 0
6 msg.position = (1, 2, 3)
7 msg.orientation = (1, 0, 0, 0)
8 msg.ranges = range(15)
9 msg.num_ranges = len(msg.ranges)
10 msg.name = "example string"
11 msg.enabled = True
12 
13 lc = lcm.LCM()
14 lc.publish("EXAMPLE", msg.encode())

The full example is available in runnable form as examples/python/send_message.py in the LCM source distribution.

For the most part, this example should be pretty straightforward. The application creates a message, fills in the message data fields, then initializes LCM and publishes the message.

The call to lcm.publish() serializes the data into a byte stream and transmits the packet to any interested receivers. The string "EXAMPLE" is the channel name, which is a string transmitted with each packet that identifies the contents to receivers. Receivers subscribe to different channels using this identifier, allowing uninteresting data to be discarded quickly and efficiently.

Receiving LCM Messages

As discussed above, each LCM message is transmitted with an attached channel name. You can use these channel names to determine which LCM messages your application receives, by subscribing to the channels of interest. It is important for senders and receivers to agree on the channel names which will be used for each message type.

Here is a sample program that sets up LCM and adds a subscription to the "EXAMPLE" channel. Whenever a message is received on this channel, its contents are printed out. If messages on other channels are being transmitted over the network, this program will not see them because it only has a subscription to the "EXAMPLE" channel. A particular instance of LCM may have an unlimited number of subscriptions.

1 import lcm
2 from exlcm import example_t
3 
4 def my_handler(channel, data):
5  msg = example_t.decode(data)
6  print("Received message on channel \"%s\"" % channel)
7  print(" timestamp = %s" % str(msg.timestamp))
8  print(" position = %s" % str(msg.position))
9  print(" orientation = %s" % str(msg.orientation))
10  print(" ranges: %s" % str(msg.ranges))
11  print(" name = '%s'" % msg.name)
12  print(" enabled = %s" % str(msg.enabled))
13  print("")
14 
15 lc = lcm.LCM()
16 subscription = lc.subscribe("EXAMPLE", my_handler)
17 
18 try:
19  while True:
20  lc.handle()
21 except KeyboardInterrupt:
22  pass

The full example is available in runnable form as examples/python/listener.py in the LCM source distribution.

After initializing the LCM object, the application subscribes to a channel by passing a callback function to the lcm.subscribe method.

The example application then repeatedly calls lcm.handle, which simply waits for a message of interest to arrive and then invokes the appropriate callback functions. Callbacks are invoked one at a time, so there is no need for thread synchronization.

If your application has other work to do while waiting for messages (e.g., print out a message every few seconds or check for input somewhere else), you can use the lcm.fileno method to obtain a file descriptor. This file descriptor can then be used in conjunction with the Python select module or some other event loop to check when LCM messages have arrived. See examples/python/listener_select.py in the LCM source distribution for an example.