Correct Base64 encoding for downlink

Hi!

I am at my wits end, trying to figure out how to properly encode an integer for downlink to a node.

The simple synopsis is that I’d like to send an unsigned short (it’ll be a number under 50,000) to a remote node which will be a sleep interval in seconds. Happy to modify this behavior to minutes if this makes it easier.

The system sending is Linux and will be transmitting via MQTT. The TTN docco states that the packet must be in Base64 format.

If I look at the raw frame from the node to the MQTT bus, I can see that ‘49320’ translates to ‘qMA=’, but I can’t get a return payload to be the same value.

I’m assuming that I need to convert the number into hex, and then into base64, but I am stumped.

Does anyone have any sample code they’re using for a similar task?

TIA.

Base64 is just a way to encapsulate binary data for inclusion in a textual protocol, how your meaning should be encoded in binary is implementation-defined.

Based on your example of 49320 ending up ‘qMA=’ you appear to be using “little endian” encoding, which seems dominant in today’s hardware, however “big endian” appears in enough standards to be often referred to as “network byte order”.

In something like python, you could do this:

import struct
import base64

value = 49320

bytes = struct.pack('<H', value) # < means little endian H is an unsigned short
#or alternately
bytes = struct.pack('>H', value) # > means big endian H is an unsigned short

#and then base64 encode
encoded = base64.b64encode(bytes)
2 Likes

Fantastic. Thank you so much for your help!