how can i publish and subscribe an image (using mqtt in python)

3.1k views Asked by At

I use Baidu loT Core. I use two devices as clients, a database(TSDB) as server. The target function:One client send a image to database , then data bese transmits to another client. I get help from How can I publish a file using Mosquitto in python? but it still doesn't work.

send image

    import paho.mqtt.client as mqtt
    import json
    import cv2

    HOST = '************'
    PORT = 1883
    client_id = '************'
    username = '***********'
    password = '******************'
    topic = '******'
    
    
    
    # obj = userdata
    # mqttc = client
    def on_connect(mqttc, obj, flags, rc):
        print("rc: " + str(rc))
    
    
    def on_message(mqttc, obj, msg):
        print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload.decode('utf-8')))
    
    
    def on_publish(mqttc, obj, mid):
        print("mid: " + str(mid))
    
    
    def on_subscribe(mqttc, obj, mid, granted_qos):
        print("Subscribed: " + str(mid) + " " + str(granted_qos))
    
    
    def on_log(mqttc, obj, level, string):
        print(string)
    
    
    def on_disconnect(mqttc, obj, rc):
        print("unsuccess connect %s" % rc)

    mqttc = mqtt.Client(client_id)
    mqttc.username_pw_set(username, password) # thanks correction. I found I forget to connect broker.But the question is still 
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_publish = on_publish
    mqttc.on_subscribe = on_subscribe
    mqttc.on_disconnect = on_disconnect
    # Uncomment to enable debug messages
    mqttc.on_log = on_log
    mqttc.connect(HOST, PORT, 60)

    image = 'E:/_TempPhoto/0.jpg'
print(type(image))
def imageToStr(image):
    with open(image, 'rb') as f:
        image_byte = base64.b64encode(f.read())
        print(type(image_byte))
    image_str = image_byte.decode('ascii')  # byte to str
    print(type(image_str))
    return image_str

image1 = imageToStr(image)
data = {
    "engineeringdata": {
        "date": 12,
        "value": "59.3;98.5",
        "image": image1
    }
}
json_mod = json.dumps(data)
mqttc.publish(topic, json_mod, 0)
mqttc.loop_forever()

receive image

    import paho.mqtt.client as mqtt
    import cv2
    import numpy as np
    import json
    
    HOST = '*********'
    PORT = 1883
    client_id = '************'
    username = '*****************'
    password = '******************'
    topic = '***************'
    
    
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code: " + str(rc))

    def strToImage(str,filename):
       image_str= str.encode('ascii')
       image_byte = base64.b64decode(image_str)
       image_json = open(filename, 'wb')
       image_json.write(image_byte)  #将图片存到当前文件的fileimage文件中
       image_json.close()    
    
    def on_message(client, userdata, msg):
        print(msg.topic + " " + str(msg.payload)) 
        strToImage(str(msg.payload), 'E:/_TempPhoto/restore001.jpg')


    
    client = mqtt.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(HOST, PORT, 60) 
    client.subscribe(topic, 0)
    client.on_message = on_message
    client.loop_forever()
    # while True:
    #    client.loop(15)
    #    time.sleep(2)

This is my send image 's message and log. I moit a part of printed data of image by '......'

Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'client_for_test'
<class 'str'>
<class 'bytes'>
<class 'str'>
Sending PUBLISH (d0, q0, r0, m1), 'b'$iot/client_for_test/user/fortest'', ... (102800 bytes)
mid: 1
Received CONNACK (0, 0)
rc: 0
Sending PINGREQ
Received PINGRESP
Sending PINGREQ
Received PINGRESP

this is receive image 's printed message:(seems right)

Connected with result code: 0

My error case is 5. And I didn't recvice a image. But it seemed that send successfully.

Maybe it's because the send image send once and end, but the receive image can't receive rightly. I just need the most simple codes of two clients to send and receive the image through mqtt,please! Give me a hand!

Thanks for help. The previous problems have been solved. But there has new trouble. I edit the new codes, I couldn't receive the image. please, Correct my code.

2

There are 2 answers

1
Hsn On

Publisher.py

import paho.mqtt.publish as publish     
f= open("myimage.jpg")
content = f.read()
mybyteArray = bytearray(content)

mqttc.publish(topic, mybyteArray , 1)

Receiver.py

def on_message(client, userdata, msg):
  f = open('myReceivedImage.jpg','w')
  f.write(msg.payload)
  f.close()
1
ΦXocę 웃 Пepeúpa ツ On

you can encode the image to base64 before publishing it so the topic's content will be a string, example:

import base64
 
with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str