gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:59:09 28 4
gpt4 key购买 nike

我正在尝试使用 Mosquitto 和 python 将文件发布到 AWS IoT。我需要发布的文件是本地目录中的 jpg 文件。我有将数据发布到物联网所需的 key 和访问 key 。我对编程很陌生,不知道如何编写这个程序。有人能帮助我吗?如果这是非常基本的事情,我很抱歉。谢谢

我已经尝试过这个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()

最佳答案

看起来你的代码中有些东西是倒退的,或者至少难以理解。以下是将二进制文件上传到 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(+ 开销)的 block ,并将每个图像的多个图像上传到 AWS IOT,直到上传整个图像。

-雷

关于python - 如何使用 Python 中的 Mosquitto 将文件发布到 AWS-IoT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35882134/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com