如何从lambda函数通过MQTT接收回消息?

时间:2018-06-27 10:25:17

标签: python python-2.7 amazon-web-services aws-lambda aws-iot

让我向您介绍我的问题,首先我必须说我是AWS和MQTT的新手,我的意思是(不要生我的气),我的问题是:我想通过MQTT发布客户端到AWS IoT / Lambda的简单JSON {'petition':'Hola','n':0},并在发布后,lambda函数必须发送回JSON消息{'petition':'Mundo','n ':0},并且必须执行10次。当您发布消息时,代码可以正常工作,但不会接收任何消息。请我帮忙解决。

这是引号:

DEVICE ---> MQTT ---> IoT SQL语句---> AWS LAMBDA

DEVICE <--- MQTT <--- 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'

IoT SQL语句

SELECT * FROM 'Hello_World'

注意:上面的那两个是使用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()

1 个答案:

答案 0 :(得分:0)

我真的只是在API网关中设置一个API调用,以便您回调Lambda。