Lambda: Publish a MQTT Message to IOT Core inside a Lambda function with Node and SDK 3

0

Can you help me to set up a simple lambda function that publishes a MQTT message to IOT Core? I did it once with SDK 2, which worked, but the structure for SDK 3 seems to be very different. I need to update the code to SDK 3 because we want to use Node_18 as runtime.

I tried different things, but for some reason I could not find a simple example until now. Thank you very much for any help!

const { IoTDataPlaneClient, PublishCommand } = require('@aws-sdk/client-iot-data-plane');

exports.handler = async function (event) {
  const client = new IoTDataPlaneClient({
    region: 'eu-west-1',
    endpoint: ‘my-endpoint.eu-west-1.amazonaws.com',
  });
  const params = {
    topic: ‘mytopic/test',
    payload: JSON.stringify({
      key: 'value',
      message: 'Hi from lambda',
    }),
    qos: 0,
  };
  const command = new PublishCommand(params);
  try {
    const data = await client.send(command);
  } catch (error) {
    console.log('error');
  } finally {
    console.log('finally');
  }
};
nico
asked 5 months ago470 views
3 Answers
1

I do not know why but this worked for me now. If anyone can explain, feel free to do so :)

const { IoTDataPlaneClient, PublishCommand } = require('@aws-sdk/client-iot-data-plane');

exports.handler = async (event) => {
  const client = new IoTDataPlaneClient({ region: 'eu-west-1' });
  const payload = { message: 'Hello from Lambda!' };
  const topic = 'mytopic/test';

  const publishCommand = new PublishCommand({
    topic,
    payload: JSON.stringify(payload),
    qos: 0,
  });

  try {
    await client.send(publishCommand);
  } catch (error) {
    console.error(error);
  }
};
nico
answered 5 months ago
0

Hello, I can give you a code snippet. The following program uses my local computer's config and credentials, which can send messages to the AWS IoT Core and has passed the test

my nodejs version is v18.17.0

const {IoTDataPlaneClient, PublishCommand} = require('@aws-sdk/client-iot-data-plane');

/**
 * send message to AWS IoT Core topic
 * @param topicName
 * @param message
 * @returns {Promise<PublishCommandOutput>}
 */
async function awsIoTCoreMqttPublisher(topicName, message) {
    // https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-your-credentials.html
    // https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iot-data-plane/
    const client = new IoTDataPlaneClient({
        region: 'us-east-1',
        // optional
        // endpoint: "my-endpoint.eu-west-1.amazonaws.com",
    });
    // https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iot-data-plane/command/PublishCommand/
    const publishCommand = new PublishCommand({
        topic: topicName,
        payload: JSON.stringify(message),
        qos: 0,
    });

    return client.send(publishCommand);
}

// ---------------- test ----------------
// test topic
const topicName = "mytopic/test";
// test message
const message = {
    "@aws-sdk/client-iot": "^3.454.0",
    "@aws-sdk/client-iot-data-plane": "^3.454.0",
    "message": "Hi from lambda",
}
// publish message to topic
const p = awsIoTCoreMqttPublisher(topicName, message)
p.then(
    result => console.log("httpStatusCode:", result.$metadata.httpStatusCode),
    err => console.log("rejected: ", err)
)

run this javascript file Enter image description here you can use AWS IoT Core MQTT test client subscription topic and then you can see message Enter image description here

profile pictureAWS
answered 5 months ago
0

This JS program works and have "publish" permission in your lamda's policy

import { IoTDataPlaneClient, PublishCommand } from "@aws-sdk/client-iot-data-plane";
const client = new IoTDataPlaneClient({ region: 'us-east-1' });

export const handler = async (event) => {  
  const topic = '$aws/things/myDHT/shadow/name/shadow_1/update';  
  const message = {
                    "state": {
                      "desired": {
                        "welcome": "aws-iot"
                      },
                      "reported": {
                        "welcome": "aws-iot",
                        "thing_name": "myDHT",
                        "date": "20240220",
                        "time": "112101",
                        "humidity": 55.20000076,
                        "temperature": 31.39999962
                      }
                    }
};  

  const publishCommand = new PublishCommand({
    topic,
    payload: JSON.stringify(message),
    qos: 0,
  });  

  try {
    const data = await client.send(publishCommand);
    console.log(data);
  } catch (error) {
    console.error(error);
  }
};
answered 2 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions