How can I post in an MQTT theme in an Amazon AWS Lambda feature?

I would like to have a lightweight command, as I use in bash, to post something in a subject on MQTT inside the AWS Lambda function. Line by line: mosquitto_pub -h my.server.com -t "light / set" -m "on"

Background: I would like to turn on the lamp and turn it off with Alex. Alexa can launch the Lambda function, and inside this lambda function I would like to start publishing MQTT, because the lamp can listen to the MQTT topic and respond to messages there. (Maybe there are simpler solutions, but we are in a state of complex (university) network, which complicates many other approaches)

+8
amazon-web-services aws-lambda mqtt publish
source share
3 answers

If you use Python, I was able to get the AWS Lambda function to publish the AWS IoT message 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 also need to make sure that the role (in your Lambda configuration) has a policy attached to allowing access to the IoT publishing function. In the IAM → Roles section, you can add the built-in policy to your role as Lambda functions, for example:

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

The AWS SDK has two classes for working with IoT: Iot and IotData. IotData.publish is the method you are looking for. It looks like the Iot object is for working with things, and IotData is for working with MQTT and shadows. This should be explicitly stated in the MQTT and shadow documentation, but it is not.

This service (IotData) is also available in the CLI .

+1
source share

If you are using Node.js, you need to install the mqtt library. The following steps will help you download and install the mqtt library on AWS Lambda.

  • Download and install Node.js and npm on your PC.

  • Download the MQTT library for Node.js.

  • Unzip it in the nodejs directory where Node.js. is installed (On Windows 10 x64, the nodejs directory C:\Program Files\nodejs )

  • Create a folder to store the installed mqtt files. For example, D:\lambda_function .

  • Run command prompt as administrator, change directory to nodejs directory.

  • Install the mqtt library in D:\lambda_function .

     C:\Program Files\nodejs>npm install --prefix "D:\lambda_function" mqtt 

Here is a similar project .

0
source share

All Articles