Skip to main content
 首页 » 编程设计

python之如何使用 mosquitto 发送图像

2025年05月04日29shihaiming

我正在尝试在 Raspberry Pi2 中使用 MQTT mosquitto 代理(pub 和 sub)发送 jpg 图像。

这是我的 python 代码 pub.py(modified)

import paho.mqtt.client as mqtt 
 
def on_publish(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() 

它是 sub.py(modified)

import paho.mqtt.client as mqtt 
 
def on_connect(client, userdata, rc): 
    print("Connect" + str(rc)) 
    client.subscribe("image")  
 
def on_message(client, userdata, msg): 
    print "Topic : ", msg.topic 
    f = open("/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_message = on_message 
 
client.connect("test.mosquitto.org", 1883, 60) 
 
client.loop_forever() 

我的 python 版本是 2.7.9。

在我解决了一些错误之后,它似乎可以工作但没有。

当我执行 sub.py 时,它连接成功,所以我在其他终端执行 pub.py。

但是,如果没有连接消息“连接结果代码为 0”,则没有任何反应

没有错误信息,所以我不知道我的错误是什么。

请您参考如下方法:

测试代码:

要求:

  1. 安装 Mosquitto 代理
  2. 安装 paho.mqtt 包。

pub.py

import paho.mqtt.publish as publish 
MQTT_SERVER = "xxx.xxx.xxx.xxx"  #Write Server IP Address 
MQTT_PATH = "Image" 
 
f=open("image_test.jpg", "rb") #3.7kiB in same folder 
fileContent = f.read() 
byteArr = bytearray(fileContent) 
 
 
publish.single(MQTT_PATH, byteArr, hostname=MQTT_SERVER) 

一个小修改,文件权限是写字节而不是写模式。

子.py

import paho.mqtt.client as mqtt 
MQTT_SERVER = "localhost" 
MQTT_PATH = "Image" 
 
# The callback for when the client receives a CONNACK response from the server. 
def on_connect(client, userdata, flags, rc): 
    print("Connected with result code "+str(rc)) 
 
    # Subscribing in on_connect() means that if we lose the connection and 
    # reconnect then subscriptions will be renewed. 
    client.subscribe(MQTT_PATH) 
    # The callback for when a PUBLISH message is received from the server. 
 
 
def on_message(client, userdata, msg): 
    # more callbacks, etc 
    # Create a file with write byte permission 
    f = open('output.jpg', "wb") 
    f.write(msg.payload) 
    print("Image Received") 
    f.close() 
 
client = mqtt.Client() 
client.on_connect = on_connect 
client.on_message = on_message 
client.connect(MQTT_SERVER, 1883, 60) 
 
# Blocking call that processes network traffic, dispatches callbacks and 
# handles reconnecting. 
# Other loop*() functions are available that give a threaded interface and a 
# manual interface. 
client.loop_forever() 

预期输出:

能够将图像从 Raspberry Pi 传输到服务器计算机。