Encoding a Series of PER Messages Using the C Encode Functions

A common encoding application is the repetitive encoding of a series of the same type of message over and over again. For example, a sensor may be updating data and this needs to be encoded an transmitted on a recurring basis.

If a user was to repeatedly initialize and free the context structure used in the encoding of a message, performance would be adversely affected. This is not necessary however, because the context can be reused to allow multiple messages to be encoded into the same output buffer. An example showing how to do this is as follows (this is abstracted from the c/sample_per/infoObject sample program):

   #include "InfoObject.h"           /* include file generated by ASN1C */

   #define MAXMSGLEN 1024

   int main (int argc, char** argv)
   {
      Iu_ReleaseCommand releaseCommand;
      ProtocolIE_Field protocolIEs[1];
      OSCTXT    ctxt;
      OSOCTET   msgbuf[MAXMSGLEN], *msgptr;
      OSSIZE    len;

      ...

      /* Encode a message to insert as open type */

      len = encodeCause (buf1, sizeof(buf1), aligned, verbose);
      if (len == OSNULLINDEX) return -1;

      /* Populate final message structure with data from encoded open type */

      if (rtInitContext (&ctxt) != 0) {
         rtxErrPrint (&ctxt);
         return -1;
      }
      ...

      for (i = 0;; ) {
         if ((stat = asn1PE_Iu_ReleaseCommand (&ctxt, &releaseCommand)) == 0) {
            /* Do something with encoded message.. */
            msgptr = pe_GetMsgPtr64 (&ctxt, &len);
            ...

         }
         else {
            printf ("Encoding failed\n");
            rtxErrPrint (&ctxt);
            return -1;
         }

         /* update protocol ID in next message */
         if (++i < count) {
            protocolIEs[0].id++;
            pe_resetBuffer (&ctxt);
         }
         else break;
      }
      ...

   }

In this case, the call to the function pe_resetBuffer at the end of the loop is what allows the encode buffer to be used for the next message. Note the comment above that says 'Do something with the encoded message'. The message must be processed at this point because it will be overwritten in the buffer when the next message is encoded.