Search code examples
pythonpublish-subscribemqttpaho

Error when try send a file using paho.mqtt.python


I'm using paho.mqtt.python in python 2.7 and when I try to send a file (image), I see the next error:

Traceback (most recent call last):
File "/home/pi/Desktop/Device1/Scripts/mqtt_publish.py", line 39, in 
mqttc.publish(MQTT_TOPIC,byteArr,0,True)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 980, in publish
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False, info)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1988, in _send_publish
upayload = payload.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

The publish script is the next:

# Import package
import paho.mqtt.client as mqtt

# Define Variables
MQTT_HOST = "192.168.1.39" #iot.eclipse.org
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "Device1"
#MQTT_MSG = 25

def on_connect(mqttc, userdata, flags, rc):
        #Subscribe to a Topic
    mqttc.subscribe(MQTT_TOPIC, 0)
    print("Connection returned result: "+connack_string(rc))

    # Define on_publish event function
def on_publish(mqttc, userdata, mid):
    print "Message Published..."
    print("mid: " +str(mid))
    mqttc.disconect()

    # Initiate MQTT Client
mqttc = mqtt.Client(client_id="LCESS", clean_session=False)

    # Register publish callback function
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
    # Connect with MQTT Broker
    # probar mqttc.username_pw_set(username, password)
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)        

    # Publish message to MQTT Broker
f= open("/home/pi/Desktop/images/image.jpg")
filecontent = f.read()
byteArr = bytes(filecontent)

mqttc.publish(MQTT_TOPIC,byteArr,0,True)

Solution

  • The solution is the following:

    replace:

    byteArr = bytes(filecontent)
    

    to

    byteArr = bytearray(filecontent)
    

    and replace:

    connack_string(rc)
    

    to

    mqtt.connack_string(rc)
    

    Because I've imported the module: import paho.mqtt.client as mqtt