Search code examples
pythonraspberry-pipublish-subscribefile-transfermqtt

How can I publish and subscribe a image file using Mosquitto in python?


I'm a student who have been studying MQTT.

I've been trying to send a image file in a Raspberry Pi using mosquitto.

This is a pub.py

    import paho.mqtt.client as mqtt

    def on_public(mosq, userdata, mid):
        mosq.disconnect()

    client = mqtt.Client()
    client.connect("test.mosquitto.org", 1883, 60)
    f=open("1.jpg", "rb")
    fileContent = f.read()
    byteArr = bytes(fileContent)
    client.publish("image",byteArr,0)
    client.loop(5)

And this is a sub.py

    import paho.mqtt.client as mqtt

    def on_public(client, userdata, rc):
        print("Connect with result code " + str(rc))
        client.subscribe(“image”)

    def on_public(client, userdata, msg):
        print("Topic : " , msg.topic + "\n Image : " + byteArr

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("test.mosquitto.org", 1883, 60)
    client.loop(20)

The problem is I couldn't know well how can I subscribe the image which I already pub.

I think the logic is find in my head, but it doesn't work.

I've attempted a lots of ways such using write() or sth like that.

I'm so sorry if It is just a basic coding skill, but I've made a system using MQTT, R-pi.

Please help me I need your hand.


Solution

  • Under normal circumstances messages will only be delivered if the subscribing client is connected and subscribing before the message is published. (For how to get at messages published when the subscriber is disconnected search for Persistent Subscriptions)

    Your subscriber app should look something like:

    import paho.mqtt.client as mqtt
    
    def on_connect(client, userdata, rc):
        print("Connect with result code " + str(rc))
        client.subscribe(“image”)
    
    def on_message(client, userdata, msg):
        print("Topic : " , msg.topic + "\n Image : " + msg.payload
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("test.mosquitto.org", 1883, 60)
    client.loop_forever()
    

    The client.loop_forever() is the important bit to keep subscriber running rather than just for 5 seconds.

    This will print the raw bytes to the console which is not going to be all that useful. To write the image to a file try something like this

    def on_message(client, userdata, msg)
        f = open('/tmp/output.jpg', 'w')
        f.write(msg.payload)
        f.close()
    

    This would write the file to /tmp/output.jpg