2

I am trying to publish image data to MQTT (CloudMQTT) with following code, but the data is not appearing on MQTT, don't even see any data on MQTT broker.

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()

Anyone know what I am missing here?

Bence Kaulics
  • 7,843
  • 8
  • 42
  • 90
rp346
  • 175
  • 6

1 Answers1

2

This is because the message payload is way bigger than will fit into a single TCP packet so the problem is that you are not starting the Paho client network loop which will chunk the message up and stream it out to the network.

You have 2 choice.

First start the network loop in the script. This is best if you are planning on sending multiple images.

Secondly if you are just publishing 1 image then the paho client code has a single function to handle just that.

Examples of how to use both can be found in the following Stack Overflow Answer.

Bence Kaulics
  • 7,843
  • 8
  • 42
  • 90
hardillb
  • 12,813
  • 1
  • 21
  • 34