Message Identifier in Protobug Message

Viewed 1145

Is there a way to get something like an ID for a protobuf message.

E.g. I have:

syntax = "proto3";

package protobuf;

message parameters_t
{
    string audio_device = 1;
}

message master_t
{
    enum type_t
    {
        unknown = 0;
        login_rsp = 1;
    }

    type_t type = 1;
}

What I want to do in C++ is send the size over the wire, then some ID of the message and the the buffer.

E.g. paramters_t is ID 0 (statically accessible) and master_t is ID 1, so I can do in my code:

if (id == protobuf::master_t::id) {
    ...
}
else if (id == protobuf::paramters_t::id) {
    ...
}

Is there any way to achieve this without manually assigning the values? I want that to be set in the protofile somehow. It can be a constant I define myself, i dont care.

2 Answers

A typical way is to just define an enum:

enum MsgId {
  MSGID_MASTER = 0;
  MSGID_PARAMETERS = 1;
}

You can then access them in C++ like constants.

What I have done to solve this now is this (arguably not very elegant) solution of putting an enum in every message like this:

enum pt
{
    invalid = 0;
    packet_type = 3;
}

This enum is in every message, but with another value for packet_type. It looks like this:

syntax = "proto3";

package protobuf;

message parameters_t
{
    enum pt
    {
        invalid = 0;
        packet_type = 1;
    }
    string audio_device = 1;
}

message login_message_t
{
    enum pt
    {
        invalid = 0;
        packet_type = 2;
    }

    enum process_type_t
    {
        invalid_process = 0;
        player = 1;
        display = 2;
    }

    process_type_t process_type = 1;
    uint32 player_id = 2;
}

message generic_message_t
{
    enum pt
    {
        invalid = 0;
        packet_type = 3;
    }
    enum type_t
    {
        unknown = 0;
        login_done = 1;
        audio_init_success = 2;
    }

    type_t type = 1;
}

message error_message_t
{
    enum pt
    {
        invalid = 0;
        packet_type = 4;
    }

    enum error_t
    {
        unknown = 0;
        could_not_init = 1;
        could_not_open_audio_device = 2;
    }

    error_t error = 1;
    bool critical = 2;
}

The advantage of this is that I can use it in templates for a class that automatically detects the packet type and identifies it to give it to a registered handler, as it can be accessed via protobuf::error_message_t::packet_type to get the value.

Related