LCM
C++ Tutorial

Sending and receiving LCM messages with C++

Introduction

This tutorial will walk you through the main tasks for exchanging LCM messages using the C++ API. The C++ API is a header-only wrapper around the C API, and thus has all the same compilation and linking requirements. 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 C++ bindings for the example type by running

1 lcm-gen -x example_t.lcm

After running this command, you should have one file, exlcm/example_t.hpp. This file is the C++ binding for the example message type. Notice that there is no .cpp file generated: the binding is a header only. If you have the time, take a moment to open up the file and inspect the generated code.

Initializing LCM

The first task for any application that uses LCM is to initialize the library. Here's an example:

1 #include <lcm/lcm-cpp.hpp>
2 
3 int main(int argc, char ** argv)
4 {
5  lcm::LCM lcm;
6 
7  if(!lcm.good())
8  return 1;
9 
10  /* Your application goes here */
11 
12  return 0;
13 }

LCM uses the namespace lcm, and the primary communications functionality is contained in the lcm::LCM class. The constructor initializes communications, 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. 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 constructor documentation.

Once constructed, the lcm::LCM::good() method can be used to check if there were any errors initializing the LCM instance for communications.

The class destructor takes care of releasing resources and cleaning up, so it is sufficient to explicitly delete heap-allocated instances or let stack-allocated instances go out of scope.

Publishing a message

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

1 namespace exlcm
2 {
3 
4 class example_t
5 {
6  public:
7  int64_t timestamp;
8  double position[3];
9  double orientation[4];
10  int32_t num_ranges;
11  std::vector< int16_t > ranges;
12  std::string name;
13  int8_t enabled;

Notice here that fixed-length arrays in LCM appear as fixed-length C++ arrays, and that variable length arrays appear as STL vectors. More on that below.

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

1 #include <lcm/lcm-cpp.hpp>
2 #include "exlcm/example_t.hpp"
3 
4 int main(int argc, char ** argv)
5 {
6  lcm::LCM lcm;
7  if(!lcm.good())
8  return 1;
9 
10  exlcm::example_t my_data;
11  my_data.timestamp = 0;
12 
13  my_data.position[0] = 1;
14  my_data.position[1] = 2;
15  my_data.position[2] = 3;
16 
17  my_data.orientation[0] = 1;
18  my_data.orientation[1] = 0;
19  my_data.orientation[2] = 0;
20  my_data.orientation[3] = 0;
21 
22  my_data.num_ranges = 15;
23  my_data.ranges.resize(my_data.num_ranges);
24  for(int i = 0; i < my_data.num_ranges; i++)
25  my_data.ranges[i] = i;
26 
27  my_data.name = "example string";
28  my_data.enabled = true;
29 
30  lcm.publish("EXAMPLE", &my_data);
31 
32  return 0;
33 }

For the most part, this example should be pretty straightforward. Note that my_data.ranges refers to a variable length array defined by the example_t LCM type, and is represented by a STL vector in the generated C++ class. It is up to the programmer to resize it appropriately and set my_data.num_ranges to a value smaller or equal to the number of elements in that vector. When the message is encoded, my_data.num_ranges determines how many elements will actually be read and transmitted from my_data.ranges. If my_data.num_ranges is set to 0, the contents of my_data.ranges is ignored.

The call to lcm::LCM::publish() serializes the data into a byte stream and transmits the packet using LCM 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.

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

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 #include <stdio.h>
2 #include <lcm/lcm-cpp.hpp>
3 #include "exlcm/example_t.hpp"
4 
5 class Handler
6 {
7  public:
8  ~Handler() {}
9 
10  void handleMessage(const lcm::ReceiveBuffer* rbuf,
11  const std::string& chan,
12  const exlcm::example_t* msg)
13  {
14  int i;
15  printf("Received message on channel \"%s\":\n", chan.c_str());
16  printf(" timestamp = %lld\n", (long long)msg->timestamp);
17  printf(" position = (%f, %f, %f)\n",
18  msg->position[0], msg->position[1], msg->position[2]);
19  printf(" orientation = (%f, %f, %f, %f)\n",
20  msg->orientation[0], msg->orientation[1],
21  msg->orientation[2], msg->orientation[3]);
22  printf(" ranges:");
23  for(i = 0; i < msg->num_ranges; i++)
24  printf(" %d", msg->ranges[i]);
25  printf("\n");
26  printf(" name = '%s'\n", msg->name.c_str());
27  printf(" enabled = %d\n", msg->enabled);
28  }
29 };
30 
31 int main(int argc, char** argv)
32 {
33  lcm::LCM lcm;
34  if(!lcm.good())
35  return 1;
36 
37  Handler handlerObject;
38  lcm.subscribe("EXAMPLE", &Handler::handleMessage, &handlerObject);
39 
40  while(0 == lcm.handle());
41 
42  return 0;
43 }

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

After creating a handler object, the application supplies a callback method and instance variable to lcm::LCM::subscribe(). During a call to lcm::LCM::handle(), the callback method is invoked on the handler object if the appropriate message has arrived. Using templates, the callback method signature directly specifies the message type, and LCM automatically decodes the message before passing it to the callback method. This happens inside a single thread without need for concurrency, since the callback is dispatched from within the lcm::LCM::handle() method.

It is possible to use other types of callbacks as well, not just methods bound to class instances. See the lcm::LCM API reference for more information.

It is important to call lcm::LCM::handle() whenever work needs to be done by LCM. If no work is needed, the function will block until there is. For applications without another type of main loop, it is suitable to call lcm::LCM::handle() in a loop as seen above. However, many applications already use some type of event loop. In these cases, it is best to monitor the LCM file descriptor, which can be obtained with lcm::LCM::getFileno(). Whenever this file descriptor becomes readable, the application should call lcm::LCM::handle() which is guaranteed to not block in such a situation.