2

I'm simply trying to add one message to another message (up to 60 times times)

My .proto file looks as follows;

syntax = "proto3";

message FeatureFile {    
    string fileName= 2;
    string Id= 3;
    repeated Feature features = 1;
}

message Feature {
    int32 version = 1;
    int32 epochTime = 2;
    int32 noOfObs= 3;
    int32 frequency = 4;
}

I have tried to make a callback function to add repeated data, but cannot make it work.

bool encode_string(pb_ostream_t* stream, const pb_field_t* field, void* const* arg)
{
    const char* str = (const char*)(*arg);

    if (!pb_encode_tag_for_field(stream, field))
        return false;

    return pb_encode_string(stream, (uint8_t*)str, strlen(str));
}

bool encode_repeatedMsg(pb_ostream_t* stream, const pb_field_t* field, void* const* arg)
{
    const char* obj = (const char*)(*arg);
    int i;

    for (i = 0; i < 60; i++)
    {
        if (!pb_encode_tag_for_field(stream, field))
            return false;

        if (!pb_encode_submessage(stream, Feature_fields, *arg))
            return false;
    }
    return true;
}

int main()
{
    FeatureFile featurefile = FeatureFile_init_zero;

    Feature feature = Feature_init_zero;

    featurefile.fileName.arg = "092536.csv";
    featurefile.fileName.funcs.encode = &encode_string;
    featurefile.Id.arg = "";
    featurefile.Id.funcs.encode = &encode_string;
    feature.version = 1;
    feature.epochTime = 12566232;
    feature.noOfObs = 260;
    feature.frequency = 200;

    featurefile.features.funcs.encode = &encode_repeatedMsg;

I thought I could call the repeated encoding like the last line of code shows, but I doesn't allow me.

The callback itself is supposed to add 60 of the same messages (feature) to the the featurefile.

Can anyone help me here?

John Dign
  • 147
  • 1
  • 8
  • 1
    It looks like you are using `arg` in `encode_repeatedMsg`, but are not setting it in `main`. Also, did you know that you can set maximum count for the array, and you get a regular array where you can store the data? – jpa Aug 20 '19 at 13:01
  • Possible duplicate of [creating callbacks and structs for repeated field in a protobuf message in nanopb in c](https://stackoverflow.com/questions/45979984/creating-callbacks-and-structs-for-repeated-field-in-a-protobuf-message-in-nanop) – vgru Aug 20 '19 at 14:54

1 Answers1

0

I myself have never used the callbacks in nanopb. I do have been using the .options file to statically allocate the desired array size. Your case this might be a bit much as your require 60 messages but this is how you do it:

You create a file with the same name as your .proto file but give it the extension .options. You place it in the same folder as your .proto file. In that file you mention there repeated variable name and assign it a size:

# XXXX.options
FeatureFile.features max_count:16

More information on the nanopb options can be found here.

Bart
  • 1,405
  • 6
  • 32