Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

mqtt - How can I publish a file using Mosquitto in python?

I am using python-mosquitto to subscribe to my MQTT broker which support file type uploads. I can use it just fine using the -f flag when going from Mosquitto on the command line. However, I can't figure out how to use the client.publish(topic, payload) to specify a file to publish when doing it from within my python script.

Python mosquitto gives me the error TypeError: payload must be a string, bytearray, int, float or None. when I try to throw something weird at it. I have a file stored in local directory already which I want to specify as the payload of the publish.

I'm experienced with MQTT but my python is very rusty, I am assuming I need to do some type of file stream function here, but not sure how to do it.

I want to specify the image here: mqttc.publish("/v3/device/file", NEED_TO_SPECIFY_HERE)

I have tried opening the image by doing:

    f = open("/home/pi/mosq/imagecap/imagefile.jpg", "rb")
    imagebin = f.read()
    mqttc.publish("/v3/device/file", imagebin)

But that didn't work and neither did mqttc.publish("/v3/device/file", bytearray(open('/tmp/test.png', 'r').read()))

The client.publish doesnt throw an error with those, but the file is not received properly by the broker. Any ideas?

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The publish has to be the whole file at once, so you will need to read the whole file in and publish it in one go.

The following code works

#!/usr/bin/python

import mosquitto

client = mosquitto.Mosquitto("image-send")
client.connect("127.0.0.1")

f = open("data")
imagestring = f.read()
byteArray = bytes(imagestring)
client.publish("photo", byteArray ,0)

And can be received with

#!/usr/bin/python

import time
import mosquitto

def on_message(mosq, obj, msg):
  with open('iris.jpg', 'wb') as fd:
    fd.write(msg.payload)


client = mosquitto.Mosquitto("image-rec")
client.connect("127.0.0.1")
client.subscribe("photo",0)
client.on_message = on_message

while True:
   client.loop(15)
   time.sleep(2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...