It's worth noting that this is one of the areas that can have differences between Python 2 and Python 3.
Python 2 file.read()
returns a str
whereas Python 3 is bytes
. mosquitto.publish()
handles both types so you should be ok in that case, but it is something to be aware of.
I've added what I consider some minor improvements to @hardillb 's code below. Please don't accept my answer in preference to his because he wrote it originally and got there first! I would have edited his answer, but I think it's useful to see the difference.
#!/usr/bin/python
import mosquitto
def on_publish(mosq, userdata, mid):
# Disconnect after our message has been sent.
mosq.disconnect()
# Specifying a client id here could lead to collisions if you have multiple
# clients sending. Either generate a random id, or use:
#client = mosquitto.Mosquitto()
client = mosquitto.Mosquitto("image-send")
client.on_publish = on_publish
client.connect("127.0.0.1")
f = open("data")
imagestring = f.read()
byteArray = bytes(imagestring)
client.publish("photo", byteArray ,0)
# If the image is large, just calling publish() won't guarantee that all
# of the message is sent. You should call one of the mosquitto.loop*()
# functions to ensure that happens. loop_forever() does this for you in a
# blocking call. It will automatically reconnect if disconnected by accident
# and will return after we call disconnect() above.
client.loop_forever()