将图像数据发布到 MQTT 未显示

物联网 MQTT 树莓派 帕霍
2021-06-26 11:31:18

我正在尝试使用以下代码将图像数据发布到 MQTT (CloudMQTT),但数据没有出现在 MQTT 上,甚至在 MQTT 代理上也看不到任何数据。

import identity
import json
import paho.mqtt.client as mqtt
import time
import datetime
import RPi.GPIO as GPIO
import bme280
import picamera
import base64

DEVICE_ID = identity.local_hostname()

config = json.loads(open('config.json').read())
SERVER = config['mqtt1']['hostname']
PORT = int(config['mqtt1']['port'])
USER = config['mqtt1']['username']
PASSWORD = config['mqtt1']['password']

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker")
    else:
        print("Connection failed")

def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed: " + str(message.topic) + " " + str(mid) + " " + str(granted_qos))


def on_message(client, userdata, message):
    print("message topic=",message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)

client = mqtt.Client(DEVICE_ID)                 
camera = picamera.PiCamera()
camera.resolution = (1280, 720)
client.username_pw_set(USER, password=PASSWORD)   
client.on_connect= on_connect                     
client.on_subscribe= on_subscribe                  
client.on_message= on_message                     
client.connect(SERVER, port=PORT)            
client.loop_start()
topics = [("DOWN/site01/pod02",2)]                 
client.subscribe(topics)
data = {'device_id':DEVICE_ID}
PUBLISH_DATA = "UP/" + "site01/" + DEVICE_ID + "/data"
PUBLISH_IMAGE = "UP/" + "site01/" + DEVICE_ID + "/image"

try:
    while True:
        data['date'] = str(datetime.datetime.today().isoformat())
        data['temperature'],data['pressure'],data['humidity'] = bme280.readBME280All()
        data['switch1'] = GPIO.input(14)
        data['switch2'] = GPIO.input(15)
        client.publish(PUBLISH_DATA,json.dumps(data))

        camera.capture('image.jpg')
        image_data = open("image.jpg", "rb")
        image_string = image_data.read()
        imageByteArray = bytes(image_string)
        client.publish(PUBLISH_IMAGE, imageByteArray, 0)
        time.sleep(10)
except KeyboardInterrupt:
    camera.close()
    client.disconnect()
    client.loop_stop()
    GPIO.cleanup()

有人知道我在这里缺少什么吗?

1个回答

这是因为消息有效负载比单个 TCP 数据包大得多,所以问题是您没有启动 Paho 客户端网络循环,该循环会将消息分块并将其流式传输到网络。

你有2个选择。

首先在脚本中启动网络循环。如果您计划发送多个图像,这是最好的。

其次,如果您只是发布 1 个图像,那么 paho 客户端代码具有single处理该图像的功能。

可以在以下 Stack Overflow Answer 中找到如何使用两者的示例