Is .encode()/.decode() required for message payloads?

  • In the samples for the OpenDXL Python Client, and all of the solutions I've seen, the payload for any type of DXL message (event/request/response) has .encode() called on it before sending. And anyone that receives the message calls .decode() on it immediately. See below for an example of what I'm referring to:


    Why is it even necessary to encode and decode the payload if we know the data type ("string", for example)? Is there a reason to do this every time?

  • Yes, in almost every case outgoing DXL messages should be encoded and incoming messages should be decoded.


    Because the DXL message payload is simply binary data, failing to encode data types that have system dependencies (or other factors) can result in an unexpected format for the data when it is received. By using .encode(), the message sender standardizes the format of the payload so that the receiver(s) can use a matching .decode() call and smoothly interpret the payload as intended.


    To help simplify the process of writing your DXL client code, we recommend using OpenDXL Bootstrap. The bootstrapper includes the MessageUtils class, which provides methods for basic encoding/decoding objects and managing Python dictionaries as JSON payloads.

  • In most cases encode/decode will help ensure that the message payload is delivered and parsed by the receiver correctly. I ran across a case with numpy arrays where I needed to use serialization to send the data. In rare cases, you may want to consider using cPickle (its a built-in Python library for serialization)... you can import cPickle, and use cPickle.dumps to load your payload in the sender code; then use cPickle.loads on the receiver. Just remember that the max message size on DXL is currently 1 MB.


    sample snippets: