Procedure for Calling Python BER Decode Methods

The procedure to call a Python decode method for the different cases described above is basically the same. It involves the following steps:

  1. Create a decode message buffer object that describes the stream from which the value will be decoded.

  2. Invoke the decode method.

The first step is the creation of a decode message buffer object. This is normally done by invoking a class method to to specify the data source. Two standard methods that can be used for this purpose are from_bytes to specify a memory source or from_file to specify a file source. For example:

    decbuf = Asn1BerDecodeBuffer.from_file('message.dat')

The decode method itself is then invoked. In the simple case of a primitive type with no generated class, this involves invoking one of the methods defined in the decode buffer class to decode a primitive value. For example, to decode an integer, one would do:

value = decbuf.decode_integer()

. This would decode the content at the current decode buffer cursor position which is expected to be a tag-length-value (TLV) with integer universal tag and integer content.

The procedure for invoking a static method is similar. The general form is <classname>.decode(decbuf, explicit, impllen). So, for example, a class named EmployeeNumber would be generated for the following definition:

EmployeeNumber ::= [APPLICATION 2] IMPLICIT INTEGER

To decode an employee number, one would do the following:

value = EmployeeNumber.decode(decbuf)

This would check to ensure the tag value at the current decode buffer position is APPLICATION 2 tag and then parse the length and decode the content. If successful, the decoded integer value will be assigned to value data variable.

Finally, to invoke the instance method in the class generated for a constructed type, one would first create an instance of the class and then invoke the generated decode method. To decode an instance of the Name class in the employee sample, one would first create an instance of the class and then invoke the decode method:

jSmithName = Name()
jSmithName.decode(decbuf)

If successful, the attributes of the jSmithName instance will be populated with the decoded values.

A complete example showing how to invoke a decode method is as follows:

   try:

      # Step 1: create a decode message buffer object to describe the
      # message to be decoded. This example will use a file input
      # stream to decode a message directly from a binary file..

      decbuf = Asn1BerDecodeBuffer.from_file(filename)

      # Step 2: create an object of the generated type and invoke the
      # decode method..

      personnelRecord = PersonnelRecord()
      personnelRecord.decode(decbuf)

      # Step 3: process the data

      if trace:
         print("Decode was successful")
         personnelRecord.print_value("personnelRecord", 0);


   except Exception:
      tb = traceback.format_exc()
      print(tb)