如何在Python中使用Mosquitto将文件发布到AWS-IoT

时间:2016-03-09 03:07:41

标签: python amazon-s3 mqtt aws-iot

我正在尝试使用Mosquitto和python将文件发布到AWS IoT。我需要发布的文件是我本地目录中的jpg文件。我有将密钥和访问密钥发布到IoT所需的密钥和访问密钥。我是编程新手,不知道如何编写这个程序。有谁可以帮助我吗?如果这是非常基本的话,我道歉。谢谢

我已经尝试了这个How can I publish a file using Mosquitto in python?并且对我不起作用。

这就是我厌倦的方式。

> #!/usr/bin/python

import mosquitto import sys                                  
import ssl 
import paho.mqtt.client as mqtt


f = open("data") 
imagestring = f.read() 
byteArray = bytes(imagestring) 
client.publish("photo", byteArray ,0)

#called when a message is received by a topic 
def on_message(mqttc, obj, msg):
print("Received message from topic: "+msg.topic+" | QoS: "+str(msg.qos)+"Data      Received: "+str(msg.payload))

#creating a client with client-id=mqtt-test 
mqttc = mqtt.Client(client_id="mqtt-test")

mqttc.on_connect = on_connect 
mqttc.on_subscribe = on_subscribe 
mqttc.on_message = on_message

#Configure network encryption  
mqttc.tls_set("/home/username/root-CA.crt",
certfile="/home/username/6fdda68178-certificate.pem.crt",
keyfile="/home/username/6fdda68178-private.pem.key",
              tls_version=ssl.PROTOCOL_TLSv1_2,
              ciphers=None)

#connecting to aws-account-specific-iot-endpoint 
mqttc.connect("A2DL8ZE59089FKF.iot.us-west-2.amazonaws.com", port=8883) 


#the topic to publish to 
mqttc.subscribe("$aws/things/mqtt-listener/shadow/update/#", qos=1)


#automatically handles reconnecting 
mqttc.loop_forever()

1 个答案:

答案 0 :(得分:3)

看起来你的代码中有些东西倒退,或者至少很难理解。以下是将二进制文件上载到AWS IOT的一些工作代码的示例。

#!/usr/bin/python

import paho.mqtt.client as paho
import os
import socket
import ssl
from time import sleep
from random import uniform

connflag = False

def on_connect(client, userdata, flags, rc):
   global connflag
   connflag = True
   print("Connection returned result: " + str(rc))

mqttc = paho.Client()
mqttc.on_connect = on_connect

awshost = "YOURAWSHOST.iot.us-west-2.amazonaws.com"
awsport = 8883
caPath = "root-CA.crt"
certPath = "YOURCERT.pem.crt"
keyPath = "YOURKEY.pem.key"

mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

mqttc.connect(awshost, awsport, keepalive=60)

mqttc.loop_start()
while 1==1:
   sleep(0.5)
   f = open('mybinaryfile')
   imagestring = bytearray(f.read())
   f.close()

   message = '"image": { "bytearray": "' + imagestring + '"} } '
   mqttc.publish("$aws/things/rpi/shadow/update", message, qos=1)

请记住,您发布的消息必须是SMALL - 128KB是最大大小。如果您有大图像,则可能需要循环覆盖图像并将其读取为小于128KB(+开销)的块,并将每个图像的多个图像上载到AWS IOT,直到您上传完整个图像。 / p>

仪射线