Encoding PPS data

The encoding functions store PPS data in the data structure pps_encoder_t. In many cases, the same pps_encoder_t structure will be reused multiple times. To begin encoding, you call either pps_encoder_initialize() (if you are starting with a pps_encoder_t structure that has not been initialized) or pps_encoder_reset() (to start again with one that you've previously used). Following this, you make calls to functions such as pps_encoder_add_string() or pps_encoder_add_int() to add data elements. Once everything has been added, you can obtain a pointer to the encoded data by calling pps_encoder_buffer() and you can find out the length of the encoded data by calling pps_encoder_length().

The PPS encoder functions can encode both simple attribute types such as strings and numbers, as well as complex types including objects and arrays. To create objects, call the function pps_encoder_start_object() to start the object and pps_encoder_end_object() to end it. To create arrays, you use pps_encoder_start_array() and pps_encoder_end_array() instead. Objects and arrays must be properly nested.

While all the functions for adding data return a status, it's typically not necessary to check it after each call. Once any function fails, all subsequent calls will fail until the encoder is reset. Thus a reasonable strategy is to make all calls assuming they will succeed and only test the return value of pps_encoder_buffer().

To take a simple example, suppose we want to encode PPS data to represent GPS information. In this case the PPS data has a speed attribute representing the current speed, a city attribute with the name of the current city, and a position attribute that contains the latitude and longitude of the current position. You might use the following code to encode this data:

pps_encoder_t encoder;

pps_encoder_initialize(&encoder, false);
pps_encoder_start_object(&encoder, "@gps");
pps_encoder_add_double(&encoder, "speed", speed);
pps_encoder_add_string(&encoder, "city", city);
pps_encoder_start_object(&encoder, "position");
pps_encoder_add_double(&encoder, "longitude", lon);
pps_encoder_add_double(&encoder, "latitude", lat);

if ( pps_encoder_buffer(&encoder) != NULL ) {
write(fd, pps_encoder_buffer(&encoder), pps_encoder_length(&encoder));

The purpose of each call is as follows:

The resulting PPS object should look like this: