【发布时间】:2018-06-27 10:25:17
【问题描述】:
让我向您介绍我的问题,首先我必须说我是 AWS 和 MQTT 的新手,我的意思是(不要生我的气),我的问题:我想通过 MQTT 发布客户端向 AWS IoT/Lambda 发送一个简单的 JSON {'petition':'Hola', 'n':0},一旦发布,lambda 函数必须发回 JSON 消息 {'petition': 'Mundo', 'n ': 0} 并且必须执行 10 次。当您发布消息时,代码工作正常,但没有收到任何消息。我需要帮助来解决它。
这是squema:
设备 ---> MQTT ---> IoT SQL SENTENCE ---> AWS LAMBDA
设备
注意:设备在 linux 终端中运行,消息必须以某种方式出现在屏幕上。
AWS Lambda 处理程序
import json
def lambda_handler(event, context):
# TODO implement
data={}
data["petition"]="Mundo"
data["n"]=event["n"]
mensaje = event['petition']
if mensaje =='Hola':
envio=json.dumps(data)
return data
else:
return 'nada encontrado'
物联网 SQL 语句
SELECT * FROM 'Hello_World'
注意:以上 2 个是使用 lambda 函数服务实现的。
设备代码
import paho.mqtt.client as paho
import os
import socket
import ssl
import time
import json
def on_connect(client, userdata, flags, rc):
print("Connection returned result: " + str(rc) )
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
def on_message(client, userdata, msg):
print("topic: "+msg.topic)
print("payload: "+str(msg.payload))
data=json.loads(msg.payload)
if data["n"]<9 and data["petition"]=="Mundo":
data["petition"] = "Hola"
data["n"] = n+1
envio=json.dumps(data)
mqttc.publish(thingName, envio)
time.sleep(4)
def on_publish(client,userdata,missatge): #create function for callback
print("data published \n")
print "Create client instance"
mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_message = on_message
#mqttc.on_log = on_log
data={}
awshost = "a20u2bg4i3u0uq.iot.eu-west-2.amazonaws.com"
awsport = 8883
clientId = "39cfba3c326847909aa5f4544211f4a4"
thingName = "Hello_World"
caPath = "/#/rootCA.pem"
certPath = "/#/3218b320c9-certificate.pem.crt"
keyPath = "/#/3218b320c9-private.pem.key"
mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
print "connecting to browser"
mqttc.connect(awshost, awsport, keepalive=60)
mqttc.loop_start()
time.sleep(2)
print"subscribing...."
mqttc.subscribe(thingName)
print"subscribed"
time.sleep(2)
data["petition"]="Hola"
data["n"]=0
envio=json.dumps(data)
print(envio)
print "Sending..."
mqttc.publish(thingName, envio)
time.sleep(4)
print "Sent"
mqttc.disconnect()
mqttc.loop_stop()
【问题讨论】:
-
为了获得更新的消息,您必须订阅该事物。
标签: python python-2.7 amazon-web-services aws-lambda aws-iot