Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I publish to a MQTT topic in a Amazon AWS Lambda function?

Tags:

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"

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)

like image 729
matt_55_55 Avatar asked Jun 14 '16 11:06

matt_55_55


People also ask

How do I publish an IoT topic from Lambda?

In the VisualEditor that opens up, select IoT as the service, and within Actions, select 'Publish' from the 'Write' dropdown. Select 'All resources' for now (you can make the resource selection 'Specific' later on). Don't bother with 'Request conditions'. Click on 'Next: Tags' and add optional tags.

Does AWS use MQTT?

AWS IoT Core supports device connections that use the MQTT protocol and MQTT over WSS protocol and that are identified by a client ID. The AWS IoT Device SDKs support both protocols and are the recommended ways to connect devices to AWS IoT.

Which AWS service supports MQTT protocol?

AWS IoT Core supports devices and clients that use the MQTT and the MQTT over WebSocket Secure (WSS) protocols to publish and subscribe to messages, and devices and clients that use the HTTPS protocol to publish messages. All protocols support IPv4 and IPv6.


1 Answers

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"})
    )

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": [
            "*"
        ]
    }
   ]
}
like image 112
Roy Avatar answered Oct 31 '22 18:10

Roy