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

自古美人都是妖i 提交于 2019-12-02 22:26:26
Roy

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": [
            "*"
        ]
    }
   ]
}

The AWS SDK has two classes to work 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 ought to be directly referenced in the documentation on MQTT and shadows, but it isn't.

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

Khanh Ho Sy

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

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

  2. Download MQTT library for node.js.

  3. Unzip it at the nodejs directory that Node.js was installed. (In Windows 10 x64, nodejs directory is C:\Program Files\nodejs)

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

  5. Run Command Prompt as administrator, change directory to nodejs directory.

  6. Install mqtt library to D:\lambda_function.

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

Here's a similar project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!