如何在python中使用MOSQUITO发布文件?
我正在使用python mosquitto订阅支持文件类型上传的MQTT代理。在命令行上从Mosquitto开始使用-f标志时,我可以很好地使用它。但是,我不知道如何使用client.publish(主题,有效负载)在python脚本中指定要发布的文件 Python mosquitto给了我一个错误如何在python中使用MOSQUITO发布文件?,python,mqtt,Python,Mqtt,我正在使用python mosquitto订阅支持文件类型上传的MQTT代理。在命令行上从Mosquitto开始使用-f标志时,我可以很好地使用它。但是,我不知道如何使用client.publish(主题,有效负载)在python脚本中指定要发布的文件 Python mosquitto给了我一个错误TypeError:payload必须是字符串、bytearray、int、float或None。当我试图抛出一些奇怪的东西时。我已经在本地目录中存储了一个文件,我想将其指定为发布的有效负载 我对MQ
TypeError:payload必须是字符串、bytearray、int、float或None。
当我试图抛出一些奇怪的东西时。我已经在本地目录中存储了一个文件,我想将其指定为发布的有效负载
我对MQTT很有经验,但我的python非常生疏,我假设我需要在这里执行某种类型的文件流函数,但不确定如何执行
我想在这里指定映像:mqttc.publish(“/v3/device/file”,需要在这里指定)
我尝试通过以下操作打开图像:
f = open("/home/pi/mosq/imagecap/imagefile.jpg", "rb")
imagebin = f.read()
mqttc.publish("/v3/device/file", imagebin)
但这不起作用,mqttc.publish(“/v3/device/file”,bytearray(open('/tmp/test.png','r').read())
client.publish不会抛出错误,但是代理没有正确接收文件。有什么想法吗
谢谢 一次发布必须是整个文件,因此您需要读取整个文件并一次性发布 下面的代码可以工作
#!/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)
并且可以通过
#!/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)
值得注意的是,这是Python2和Python3之间可能存在差异的领域之一 Python2
file.read()
返回一个str
,而Python3是bytes
mosquitto.publish()
处理这两种类型,所以在这种情况下应该可以,但这是需要注意的
我在下面添加了一些我认为对@ HaviLB代码的一些小改进。请不要接受我的答案而不是他的答案,因为这是他最初写的,并且是第一个到达那里的!我会编辑他的答案,但我认为看到差异是有用的
#!/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()
这两个答案都有效,结果是我的代码中缺少
client.loop_forever()
,以及大量的byteArray转换都很有效。我感到奇怪的是,我能够发布像“hello world”这样的文本,而不需要永远循环,但在执行文件(大约70k)时,它需要永远循环()。谢谢你的帮助!