尝试使用paho.mqtt.python发送文件时出错

时间:2016-11-16 22:01:27

标签: python publish-subscribe mqtt paho

我在python 2.7中使用paho.mqtt.python,当我尝试发送文件(图像)时,我看到下一个错误:

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)

发布脚本是下一个:

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

2 个答案:

答案 0 :(得分:-1)

使用时出错:bytes(filecontent).decode()

 Traceback (most recent call last):
      File "/home/pi/Desktop/Device1/Scripts/mqtt_publish.py", line 37, in <module>
        byteArr = bytes(filecontent).decode()
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

答案 1 :(得分:-1)

解决方案如下:

取代:

byteArr = bytes(filecontent)

byteArr = bytearray(filecontent)

并替换:

connack_string(rc)

mqtt.connack_string(rc)

因为我导入了模块:import paho.mqtt.client as mqtt