Search code examples
pythonmqttmosquitto

Send metadata in mqtt message


I am using mqtt for the first time to transfer some binary files, so far I have no issues transferring it using a code like bellow

import paho.mqtt.client as paho
f=open("./file_name.csv.gz","rb")
filename= f.read()
f.close()
byteArray = bytearray(filename)
mqttc = paho.Client()
mqttc.will_set("/event/dropped", "Sorry, I seem to have died.")
mqttc.connect(*connection definition here*)
mqttc.publish("hello/world", byteArray )

However together with the file itself there is some extra info I want to send (the original file name, creation date,etc...), I can't find any proper way to transfer it using mqtt, is there any way to do that or do I need to add that info to the message byteArray itself? How would I do that?


Solution

  • You need to build your own data structor to hold the file and it's meta data.

    How you build that structure is up to you. A couple of options would be:

    • base64/uuencode encode the file and add it as a field in a JSON object and save the meta data as other fields then publish the JSON object.

    • Build a Python map with the file as a field and other meta data as other fields. Then use pickle to serialise the map.