最近,我尝试通过AWS IOT服务发布和订阅消息。
以下是我处理它的方式:
但是,每次我将数据发布到AWS IOT MQTT服务器时,我的订阅脚本都重新连接到MQTT服务器并且没有从远程接收数据。
以下是我的Subscribe.py
脚本:
import sys
import ssl
import paho.mqtt.client as mqtt
import time
def on_connect(mqttc, obj, flags, rc):
if rc==0:
print ("Connection status: successful")
elif rc==1:
print ("Connection status: Connection refused")
mqttc.subscribe("Sensor/+/reading", qos=1)
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos)+"data"+str(obj))
def on_message(mqttc, obj, msg):
print("TOPIC: "+msg.topic+"| Data Received: "+str(msg.payload))
mqttc = mqtt.Client(client_id="Yun")
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.tls_set("root-CA.crt",
certfile="64bc41eab8-certificate.pem.crt",
keyfile="64bc41eab8-private.pem.key",
tls_version=ssl.PROTOCOL_TLSv1_2,
ciphers=None)
mqttc.connect("AWS Thing endpoint",port = 8883)
mqttc.loop_forever()
这是我的Publish.py
脚本:
import sys
import ssl
import json
import time
import paho.mqtt.client as mqtt
jsonstr = '{"DeviceId":0,"Readings":[{"label":"Light","data":223},{"label":"Motion","data":245}]}'
jsonReading = json.loads(jsonstr)
payloadJson = {}
payloadJson['state'] = {}
payloadJson['state']['desired'] = jsonReading
print payloadJson
def on_publish(mosq, obj, mid):
print("mid: "+str(mid))
def on_connect(mqttc, obj, flags, rc):
if rc==0:
print ("Connection status: successful")
elif rc==1:
print ("Connection refused")
return
def on_disconnect(client, userdata, rc):
print("disonnected")
mqttc = mqtt.Client(client_id="Yun")
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.tls_set("root-CA.crt",
certfile="64bc41eab8-certificate.pem.crt",
keyfile="64bc41eab8-private.pem.key",
tls_version=ssl.PROTOCOL_TLSv1_2,
ciphers=None)
mqttc.connect("AWS iot things endpoint",8883)
mqttc.loop_start()
while True:
mqttc.publish("Sensor/livingroom/reading", json.dumps(payloadJson) , qos = 1)
time.sleep(10)
答案 0 :(得分:1)
解决!一个AWS iot Thing无法连接两件事(连接)。只需在AWS iot中添加一个用于提取连接的内容,脚本就可以正常运行。
答案 1 :(得分:0)
MQTT客户端ID必须是唯一的。您正在为两个客户使用Yun的客户端ID。
MQTT规范说当第二个客户端使用相同的客户端ID连接时,代理必须断开第一个客户端。