You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过触发式Lambda函数处理MQTT消息并发送至另一AWS IoT主题?

Solution: Generate and Publish Custom Messages via Lambda from AWS IoT Rule

Got it, let's walk through exactly how to build this Lambda function to generate a custom message and publish it to your target topic. Since the built-in "Republish" action only forwards the original message, using Lambda gives you full control to transform or create entirely new content.

Step 1: Set Up Lambda IAM Permissions

First, your Lambda function needs permission to publish messages to AWS IoT Core. You'll need to add an inline policy to your Lambda's execution role:

  1. Go to the IAM console, find your Lambda's execution role.
  2. Add an inline policy with the following JSON (replace REGION and ACCOUNT_ID with your actual values):
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iot:Publish",
            "Resource": "arn:aws:iot:REGION:ACCOUNT_ID:topic/terminal2/test"
        }
    ]
}

This policy explicitly grants the Lambda permission to send messages to your terminal2/test topic.

Step 2: Write the Lambda Function Code

Below is a Python example (the most common choice for AWS Lambda) that handles the incoming IoT message, generates a custom new message, and publishes it to your target topic. I've included comments to explain each part:

import boto3
import json
import base64

# Initialize the AWS IoT Data Plane client
iot_data_client = boto3.client('iot-data')

def lambda_handler(event, context):
    # Parse the incoming message from the IoT rule
    # Note: IoT rules often encode the payload as base64 by default
    try:
        # Decode base64 payload and convert to JSON
        raw_payload = base64.b64decode(event['payload']).decode('utf-8')
        original_message = json.loads(raw_payload)
    except KeyError:
        # Fallback if payload is already decoded (adjust based on your rule config)
        original_message = event.get('payload', {})
    except json.JSONDecodeError:
        # Handle cases where original message isn't valid JSON
        original_message = {"raw_message": raw_payload}

    # --------------------------
    # Customize this section to generate your new message
    # --------------------------
    new_message = {
        "original_content": original_message,
        "processed_at": context.get_remaining_time_in_millis(),
        "message_type": "transformed",
        "custom_metadata": {
            "source_topic": "terminal1/",
            "status": "success"
        }
    }

    # Publish the new message to terminal2/test
    try:
        publish_response = iot_data_client.publish(
            topic='terminal2/test',
            qos=1,  # Use 0 for fire-and-forget, 1 for guaranteed delivery
            payload=json.dumps(new_message)
        )
        print(f"Message published successfully: {publish_response}")
        return {
            "statusCode": 200,
            "body": json.dumps("Custom message published to terminal2/test")
        }
    except Exception as e:
        error_msg = f"Failed to publish message: {str(e)}"
        print(error_msg)
        return {
            "statusCode": 500,
            "body": json.dumps(error_msg)
        }

Key Notes About the Code:

  • Payload Decoding: AWS IoT rules typically pass the message payload as a base64-encoded string, so we handle that decoding first. If your rule is configured to pass raw JSON, you can skip the base64 step.
  • Custom Message Logic: The new_message dictionary is where you'll define your custom content—you can modify this to include any data derived from the original message, static values, or external data.
  • QoS Setting: Adjust the qos parameter based on your delivery needs: 0 for best-effort, 1 for at-least-once delivery.

Step 3: Update Your AWS IoT Rule

Make sure your existing IoT rule is configured to trigger this Lambda function instead of the republish action:

  1. Go to the AWS IoT Core console, open your rule.
  2. Under "Actions", remove the existing republish action (if present).
  3. Add a new action: Invoke a Lambda function.
  4. Select your newly created Lambda function from the dropdown list.
  5. Save the rule.

Step 4: Test the Workflow

  1. Use an MQTT client (like the AWS IoT Core Test Console, or a tool like Mosquitto) to publish a message to terminal1/.
  2. Subscribe to the terminal2/test topic in the same client.
  3. You should see your custom generated message appear in the subscription feed.

内容的提问来源于stack exchange,提问作者Senura Dissanayake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:00:00