Search code examples
nanopb

nanopb encode always size 0 (but no encode failure)


I have a very simple proto:

syntax = "proto2";

message TestMessage {
    optional int32 val = 1;
    optional string msg = 2;  // I set max size to 40 in options, so TestMessage_size is defined.
}

...and I have the following code in my main loop for an arduino program:

  TestMessage test_msg = TestMessage_init_zero;
  test_msg.val = 123;

  // Print message length.
  size_t msg_length;
  bool get_msg_length = pb_get_encoded_size(&msg_length, TestMessage_fields, &test_msg);
  Serial.println(msg_length);

  // Encode and print message.
  uint8_t testbuffer[TestMessage_size];
  pb_ostream_t teststream = pb_ostream_from_buffer(testbuffer, sizeof(testbuffer));
  bool teststatus = pb_encode(&teststream, TestMessage_fields, &test_msg);
  if (!teststatus) {
    Serial.println("Failed to encode test message.");
    return;
  }
  Serial.print("Message: ");
  Serial.println(teststream.bytes_written);
  for(size_t i = 0; i < teststream.bytes_written; i++){
    Serial.print(testbuffer[i], OCT);
  }
  Serial.println("testbuffer flushed");

For some reason I can print test_msg.val and it will show 123 but when I try to encode it (following examples like this one) it always is empty / has size 0.

Is this a configuration issue with nanopb? I wonder if the encode method requires something that I am not using?


Solution

  • For optional fields, you also have to set the has_field:

    TestMessage test_msg = TestMessage_init_zero;
    test_msg.has_val = true;
    test_msg.val = 123;
    

    That's because otherwise there is no way to know if the optional field has been set or not. C++ handles this via setter methods, but C doesn't have those.