ahnstar ahnstar - 6 months ago 250
Python Question

How can I send a image by using mosquitto?

I'm a student who is studying MQTT and I'm trying to send a jpg image using MQTT mosquitto broker(pub and sub) in Raspberry Pi2.

I've solved many error, however, It doesn't work.

This is my python code pub.py(modified)

import paho.mqtt.client as mqtt

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

client = mqtt.Client()
client.connect("test.mosquitto.org", 1883, 60)
client.on_publish = on_publish

f=open("b.jpg", "rb") #3.7kiB in same folder
fileContent = f.read()
byteArr = bytearray(fileContent)
client.publish("image",byteArr,0)

client.loop_forever()


and it's sub.py(modified)

import paho.mqtt.client as mqtt

def on_connect(client, userdata, rc):
print("Connect" + str(rc))
client.subscribe("image")

def on_publish(client, userdata, msg):
print "Topic : ", msg.topic
f = open("home/pi/tmp/output.jpg", "w") #there is a output.jpg which is different
f.write(msg.payload)
f.close()

client = mqtt.Client()
client.on_connect = on_connect
client.on_publish = on_publish

client.connect("test.mosquitto.org", 1883, 60)

client.loop_forever()


My python verson is 2.7.9.

After I solved some error, It seems to work but It doesn't.

When I implement the sub.py, It connects successfully so I implement the pub.py in other terminal.

However, There isn't any reaction without connect message which is "Connect with result code 0"

There is no error message so I don't know what my mistake is.

My code is wrong? I think it ok.

I'm so sorry if It is just a basic coding skill.

Please help me I need your hand.

Answer

In sub.py you have 2 on_public functions which should be renamed on_connect and on_publish respectively.

In pub.py you need to actually set the on_publish method on the client so it will be called once the publish has been completed.

...
client.connect("test.mosquitto.org", 1883, 60)
client.on_publish = on_public
...

Also as @ralight pointed out in his answer to your previous question, you should change client.loop(5) to client.loop_forever() it will still exit once the message has been sent because of the mosq.disconnect()