7.1.2. Protobuf: Person#

In the last section you learned how to send strings to an eCAL Topic. Using strings is great for simple data that has a textual representation. Quite often however your data will be more complex, so you need some kind of protocol that defines how your data is structured.

Our recommended way is to use Google protobuf to do that, because:

  • It solves the problem of how to serialize and de-serialize data for you

  • You get downward compatibility out of the box (if you follow the guidelines)

  • It is maintained by Google and the API is stable

  • The eCAL Monitor can display a nice reflection view of the data

Important

It is important to remember, that all your applications must agree on the data format. As protobuf messages are defined in .proto files, all of your applications should share the same files.

eCAL supports protobuf serialization natively for C++, C# and Python.

The usage of protobuf for data exchange in eCAL is very simple. You know already from the “String: Hello World” how to send and receive simple string data. The basic setup will be the same, but instead of using the string publisher, we will use the protobuf publisher and subscriber.

7.1.2.1. Person Protobuf#

As the sender and receiver need the same .proto files, we place them in a separate directory next to the source directories for the sender and the receiver.

 Person Protobuf File
├─  person.proto
│
├─  animal.proto
│
└─  house.proto

Let’s start with the protobuf/person.proto file!

 1syntax = "proto3";
 2
 3// import message definitions from different proto files
 4import "animal.proto";
 5import "house.proto";
 6
 7// assign a package name, that will appear as a namespace
 8package pb.People;
 9
10// create the message "Person" with
11//   - base types like int32 and string
12//   - individual defined enum SType
13//   - imported message types
14message Person
15{
16  enum SType
17  {
18    MALE   = 0;
19    FEMALE = 1;
20  }
21
22  int32  id               = 1;
23  string name             = 2;
24  SType  stype            = 3;
25  string email            = 4;
26
27  Animal.Dog        dog   = 5;
28  Environment.House house = 6;
29}

As you can see, the person.proto file imports also other message definitions: animal.proto and house.proto. So we need them as well. The definitions are straight forward. For more information about protobuf, please refer to the detailed official documentation.

1syntax = "proto3";
2
3package pb.Animal;
4
5message Dog
6{
7  string name   = 1;
8  string colour = 2;
9}
1syntax = "proto3";
2
3package pb.Environment;
4
5message House
6{
7  int32 rooms = 1;
8}

7.1.2.2. Person Publisher#

The main differences to the string publisher are:
  • we need to include the protobuf publisher from ecal/msg/protobuf/publisher.h

  • also we need the compiled protobuf message header file person.pb.h and include it

  • we need to utilize the protobuf message class Person instead of the string class std::string

  1// Including the eCAL convenience header
  2#include <ecal/ecal.h>
  3// In addition we include the msg protobuf publisher
  4#include <ecal/msg/protobuf/publisher.h>
  5
  6#include <iostream>
  7
  8// Here we include the compiled protobuf header for the message "Person"
  9#include "person.pb.h"
 10
 11int main()
 12{
 13  std::cout << "--------------------" << std::endl;
 14  std::cout << " C++: PERSON SENDER"  << std::endl;
 15  std::cout << "--------------------" << std::endl;
 16
 17  /*
 18    Initialize eCAL. You always have to initialize eCAL before using its API.
 19    The name of our eCAL Process will be "person send". 
 20    This name will be visible in the eCAL Monitor, once the process is running.
 21  */
 22  eCAL::Initialize("person send");
 23
 24  /*
 25    Print some eCAL version information.
 26  */
 27  std::cout << "eCAL " << eCAL::GetVersionString() << " (" << eCAL::GetVersionDateString() << ")" << "\n";
 28
 29  /*
 30    Set the state for the program.
 31    You can vary between different states like healthy, warning, critical ...
 32    This can be used to communicate the application state to applications like eCAL Monitor/Sys.
 33  */
 34  eCAL::Process::SetState(eCAL::Process::eSeverity::healthy, eCAL::Process::eSeverityLevel::level1, "I feel good!");
 35
 36  /*
 37    Now we create a new publisher that will publish the topic "person".
 38    The data type is "pb.People.Person", generated from the protobuf definition.    
 39  */
 40  eCAL::protobuf::CPublisher<pb::People::Person> publisher("person");
 41
 42  /*
 43    Construct a message. The message is a protobuf struct that will be sent to the subscribers.
 44  */
 45  pb::People::Person person;
 46  person.set_id(0);
 47  person.set_name("Max");
 48  person.set_stype(pb::People::Person_SType_MALE);
 49  person.set_email("max@mail.net");
 50  person.mutable_dog()->set_name("Brandy");
 51  person.mutable_house()->set_rooms(4);
 52
 53  /*
 54    Creating an infinite publish-loop.
 55    eCAL Supports a stop signal; when an eCAL Process is stopped, eCAL_Ok() will return false.
 56  */
 57  auto loop_count = 0;
 58  while(eCAL::Ok())
 59  {
 60    /*
 61      Change in each loop the content of the message to see a difference per message.
 62    */
 63    person.set_id(loop_count++);
 64
 65    /*
 66      Send the message. The message is sent to all subscribers that are currently connected to the topic "person".
 67    */
 68    if (publisher.Send(person)) 
 69    {
 70      std::cout << "----------------------------------"        << "\n";
 71      std::cout << "Sent protobuf message in C++: "            << "\n";
 72      std::cout << "----------------------------------"        << "\n";
 73      std::cout << "person id    : " << person.id()            << "\n";
 74      std::cout << "person name  : " << person.name()          << "\n";
 75      std::cout << "person stype : " << person.stype()         << "\n";
 76      std::cout << "person email : " << person.email()         << "\n";
 77      std::cout << "dog.name     : " << person.dog().name()    << "\n";
 78      std::cout << "house.rooms  : " << person.house().rooms() << "\n";
 79      std::cout << "----------------------------------"        << "\n";
 80      std::cout                                                << "\n";
 81    }
 82    else
 83    {
 84      std::cout << "Failed to send Protobuf message in C++!"   << "\n";
 85    }
 86
 87    /*
 88      Sleep for 500ms to send in a frequency of 2 hz.
 89    */
 90    eCAL::Process::SleepMS(500);
 91  }
 92
 93  /*
 94    Finalize eCAL. This will stop all eCAL processes and free all resources.
 95    You should always finalize eCAL when you are done using it.
 96  */
 97  eCAL::Finalize();
 98
 99  return(0);
100}

7.1.2.3. Person Publisher Files#


├─  C++
│  └─  person_send.cpp
│
├─  C#
│  └─  person_send_csharp.cs
│
└─  Python
   └─  person_send.py

7.1.2.4. Person Subscriber#

For the subscriber the same changes apply as for the publisher.

 1// Including the eCAL convenience header
 2#include <ecal/ecal.h>
 3// In addition we include the msg protobuf publisher
 4#include <ecal/msg/protobuf/subscriber.h>
 5
 6#include <iostream>
 7
 8#include "person.pb.h"
 9
10/*
11  Here we create the subscriber callback function that is called everytime,
12  when a new message arrived from a publisher.
13*/
14void OnPerson(const eCAL::STopicId& topic_id_, const pb::People::Person& person_, const long long time_, const long long clock_)
15{
16  std::cout << "------------------------------------------"                    << "\n";
17  std::cout << " Received Protobuf message in C++ "                            << "\n";
18  std::cout << "------------------------------------------"                    << "\n";
19  std::cout << " topic name   : " << topic_id_.topic_name                      << "\n";
20  std::cout << " topic time   : " << time_                                     << "\n";
21  std::cout << " topic clock  : " << clock_                                    << "\n";
22  std::cout << ""                                                              << "\n";
23  std::cout << " Content of message type \"" << person_.GetTypeName()  << "\"" << "\n";
24  std::cout << "------------------------------------------"                    << "\n";
25  std::cout << " id          : " << person_.id()                               << "\n";
26  std::cout << " name        : " << person_.name()                             << "\n";
27  std::cout << " stype       : " << person_.stype()                            << "\n";
28  std::cout << " email       : " << person_.email()                            << "\n";
29  std::cout << " dog.name    : " << person_.dog().name()                       << "\n";
30  std::cout << " house.rooms : " << person_.house().rooms()                    << "\n";
31  std::cout << "------------------------------------------"                    << "\n";
32  std::cout                                                                    << "\n";
33}
34
35int main()
36{
37  std::cout << "----------------------" << std::endl;
38  std::cout << " C++: PERSON RECEIVER"  << std::endl;
39  std::cout << "----------------------" << std::endl;
40
41  /*
42    Initialize eCAL. You always have to initialize eCAL before using its API.
43    The name of our eCAL Process will be "person receive". 
44    This name will be visible in the eCAL Monitor, once the process is running.
45  */
46  eCAL::Initialize("person receive");
47
48  /*
49    Print some eCAL version information.
50  */
51  std::cout << "eCAL " << eCAL::GetVersionString() << " (" << eCAL::GetVersionDateString() << ")" << "\n";
52
53  /*
54    Set the state for the program.
55    You can vary between different states like healthy, warning, critical ...
56    This can be used to communicate the application state to applications like eCAL Monitor/Sys.
57  */
58  eCAL::Process::SetState(eCAL::Process::eSeverity::healthy, eCAL::Process::eSeverityLevel::level1, "I feel good!");
59
60  /*
61    Creating the eCAL Subscriber. An eCAL Process can create multiple subscribers (and publishers).
62    The topic we are going to receive is called "person".
63    The data type is "Pb.People.Person", generated from the protobuf definition.
64  */
65  eCAL::protobuf::CSubscriber<pb::People::Person> subscriber("person");
66
67  /*
68    Create and register a receive callback. The callback will be called whenever a new message is received.
69  */
70  subscriber.SetReceiveCallback(&OnPerson);
71
72  /*
73    Creating an infinite loop.
74    eCAL Supports a stop signal; when an eCAL Process is stopped, eCAL::Ok() will return false.
75  */
76  while(eCAL::Ok())
77  {
78    /*
79      Sleep for 500ms to avoid busy waiting.
80    */
81    eCAL::Process::SleepMS(500);
82  }
83
84  /*
85    Finalize eCAL. This will stop all eCAL processes and free all resources.
86    You should always finalize eCAL before exiting your application.
87  */
88  eCAL::Finalize();
89  
90  return(0);
91}

7.1.2.5. Person Subscriber Files#


├─  C++
│  └─  person_receive.cpp
│
├─  C#
│  └─  person_receive_csharp.cs
│
└─  Python
   └─  person_receive.py