【问题标题】:How Can I Publish File to AWS- IoT using Mosquitto in Python如何在 Python 中使用 Mosquitto 将文件发布到 AWS-IoT
【发布时间】:2016-06-23 06:28:11
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

  • 解释您指向的示例如何不起作用以及您如何更改它

标签: python amazon-s3 mqtt aws-iot


【解决方案1】:

您的代码中似乎有些东西倒退了,或者至少难以理解。这是将二进制文件上传到 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)

请记住,您发布的消息需要很小 - 128KB 是最大大小。如果您有大图像,您可能需要遍历您的图像并将其读入小于 128KB(+ 开销)的块,然后为每个图像上传多个图像到 AWS IOT,直到您上传整个图像。

-雷

【讨论】:

  • @ Ray Terrill 当我运行这段代码时,它说连接返回结果:0。它也没有更新阴影。有什么建议 ?我插入了我的图片路径,上面写着 f = open('mybinaryfile'),这是正确的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2022-06-12
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多