I'm using protobuf/nanoPB to exchange data between a micro controller and a raspberry pi. I'm relatively new to nanoPB and struggle a bit with repeated fields. In the example below I set all the values except for the repeated temperature fields, and it works great.
Proto file:
syntax = "proto2";
message SimpleMessage
{
message TemperatureSensorData
{
optional int32 temperature = 1;
optional int32 errorFlag = 2;
}
message Motor
{
optional int32 id = 1;
optional int32 voltage = 2;
optional int32 current = 3;
repeated TemperatureSensorData motorTemperature = 4;
}
optional Motor motor = 1;
}
Simple example program to encode and decode:
#include <iostream>
#include <stdlib.h>
#include <pb_encode.h>
#include <pb_decode.h>
#include "SimpleRepeated.pb.h"
int main(int argc, char *argv[])
{
uint8_t buffer[128];
size_t message_length;
bool status;
/* Encode */
{
SimpleMessage message = SimpleMessage_init_zero;
/* Create a stream that will write to our buffer. */
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// Fill in data
message.has_motor = true;
message.motor.has_id = true;
message.motor.id = 1;
message.motor.has_voltage = true;
message.motor.voltage = 24;
message.motor.has_current = true;
message.motor.current = 3;
/* Now we are ready to encode the message! */
status = pb_encode(&stream, SimpleMessage_fields, &message);
message_length = stream.bytes_written;
/* Then just check for any errors.. */
if (!status)
{
printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
return 1;
}
}
/* Decode */
{
/* Allocate space for the decoded message. */
SimpleMessage message = SimpleMessage_init_zero;
/* Create a stream that reads from the buffer. */
pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
/* Now we are ready to decode the message. */
status = pb_decode(&stream, SimpleMessage_fields, &message);
/* Check for errors... */
if (!status)
{
printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
return 1;
}
/* Print the data contained in the message. */
std::cout << "ID= " << message.motor.id << std::endl;
std::cout << "Voltage= " << message.motor.voltage << std::endl;
std::cout << "Current= " << message.motor.current << std::endl;
}
return 0;
}
What is the easiest way of adding temperature values? I tried something like this:
for(uint8_t i=0; i<5; i++)
{
message.motor.motorTemperature[i].temperature = i;
message.motor.motorTemperature[i].errorFlag = i*i;
}
but it won't compile. The l
Best regards,
Sondre
Thank you, Petteri!
It worked perfectly :)
Best regards
Sondre