如何在 Amazon AWS Lambda 函数中发布到 MQTT 主题? [英] How can I publish to a MQTT topic in a Amazon AWS Lambda function?
问题描述
我想要一个简单的命令,就像我在 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屋!