如何在Amazon AWS Lambda函数中发布到MQTT主题? [英] How can I publish to a MQTT topic in a Amazon AWS Lambda function?

查看:397
本文介绍了如何在Amazon AWS Lambda函数中发布到MQTT主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个简单的命令,就像我在bash中使用的那样,将一些内容发布到AWS Lambda函数内的MQTT主题上.遵循以下原则: mosquitto_pub -h my.server.com -t"light/set" -m"on"

I would like to have an easy command like I use in the bash to publish something to a topic on MQTT inside a AWS Lambda function. Along the lines of: mosquitto_pub -h my.server.com -t "light/set" -m "on"

背景:我想用Alexa打开和关闭一个灯. Alexa可以启动Lambda函数,并且在此Lambda函数中,我想启动MQTT发布,因为指示灯可以收听MQTT主题并对那里的消息做出反应.(也许有更简单的解决方案,但是我们处于复杂的(大学)网络,这使得许多其他方法变得更加困难)

Background: I would like to turn a lamp on and off with Alexa. Alexa can start a Lambda function, and inside of this Lambda function I would like to start an MQTT publish, because the lamp can listen to a MQTT topic and react on the messages there.(Maybe there are easier solutions, but we are in a complicated (university) network which makes many other approaches more difficult)

推荐答案

如果您使用的是Python,则可以使用处理程序函数中的以下内容获取AWS Lambda函数以将消息发布到AWS IoT:

If you are using Python, I was able to get an AWS Lambda function to publish a message to AWS IoT using the following inside my handler function:

import boto3
import json

client = boto3.client('iot-data', region_name='us-east-1')

# Change topic, qos and payload
response = client.publish(
        topic='$aws/things/pi/shadow/update',
        qos=1,
        payload=json.dumps({"foo":"bar"})
    )

您还需要确保角色(在Lambda函数配置中)具有附加的策略,以允许访问IoT发布功能.在IAM->角色下,您可以向Lambda函数角色添加内联策略,例如:

You will also need to ensure that the Role (in your Lambda function configuration) has a policy attached to allow access to IoT publish function. Under IAM -> Roles you can add an inline policy to your Lambda function Role like:

{
   "Version": "2016-6-25",
   "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "iot:Publish"
        ],
        "Resource": [
            "*"
        ]
    }
   ]
}

这篇关于如何在Amazon AWS Lambda函数中发布到MQTT主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆