0

I'm working on creating a MQTT test in Python using paho-mqtt and I need to be able to send an array of bytes to my broker. A subscriber looks for several topics of different data types. The string based payloads are working fine but numerical values must be received in an array of bytes the proper length for the numerical type (i.e. 32 bit Integers must be an array of 4 bytes)

For example to send an 32 bit integer (INT32) the payload would be 00 00 00 00

If I want to send a decimal 53 I would need to send 00 00 00 35 (0x35 = 53)

As this test is ran as part of a suite it needs to be in Python and paho-mqtt is what we chose as our mqtt package.

If anyone could please tell me how to use paho-mqtt to transmit an array of bytes it would be greatly appreciated.

Jason Templeman
  • 431
  • 5
  • 21

1 Answers1

1

Use the python struct module to pack binary data. For example:

import struct
struct.pack('i', 53)

will yield:

'5\x00\x00\x00'

(note: the '5' is just the ASCII value for 53, using your example).

Also, to explicitly specify endian-ness (byte ordering), use:

struct.pack('>i', 53)

This will yield bytes reversed:

'\x00\x00\x005'

You can use a repeat count to specify arrays. For example, the '10i' means an array of 10 32-bit integers, 4 bytes each, 40 bytes total.

For more information, see the struct module documentation: https://docs.python.org/2.7/library/struct.html

payne
  • 13,833
  • 5
  • 42
  • 49