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

Cognito认证WebSocket连接AWS IoT Core订阅成功却收不到消息

问题:WebSocket连接AWS IoT Core成功但无法接收消息

我正尝试通过JavaScript经WebSocket连接AWS IoT Core,采用Amazon Cognito身份池进行认证。连接已成功(日志确认),且主题订阅操作也完成,但无法接收任何消息——尽管通过AWS测试客户端可验证消息正被主动发布。我已为Cognito使用的未认证角色授予权限,也为设备所用证书附加了策略。

使用的IAM策略

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect",
        "iot:Subscribe",
        "iot:Receive",
        "iot:Publish"
      ],
      "Resource": "*"
    }
  ]
}

JavaScript代码

// --- Configuration ---
const AWS_REGION = '';
const COGNITO_IDENTITY_POOL_ID = '';
const IOT_CORE_ENDPOINT = '';
const MQTT_TOPIC = ''; 

// --- DOM Elements ---
const connectionStatusElement = document.getElementById('connection-status');
const iotDataElement = document.getElementById('iot-data');
const reconnectButton = document.getElementById('reconnect-button');

let connection; // Declare connection globally to manage its state

// --- Function to get AWS Credentials from Cognito ---
async function getAWSCredentials() {
    AWS.config.region = AWS_REGION;
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: COGNITO_IDENTITY_POOL_ID
    });

    try {
        await AWS.config.credentials.getPromise();
        console.log('Successfully got AWS credentials from Cognito.');
        return {
            accessKeyId: AWS.config.credentials.accessKeyId,
            secretAccessKey: AWS.config.credentials.secretAccessKey,
            sessionToken: AWS.config.credentials.sessionToken
        };
    } catch (error) {
        console.error('Error getting AWS credentials:', error);
        throw error; // Propagate the error
    }
}

// --- Function to Connect to AWS IoT Core and Subscribe ---
async function connectAndSubscribe() {
    connectionStatusElement.textContent = 'Connecting...';
    reconnectButton.style.display = 'none';

    try {
        const credentials = await getAWSCredentials();

        const clientID = `web_client_${Math.random().toString(16).substr(2, 8)}`; // Unique client ID

        // Initialize the AWS IoT MQTT Connection
        connection = new iot.AwsIotMqttConnection({
            endpoint: IOT_CORE_ENDPOINT,
            protocol: iot.AwsIotMqttConnectionConfig.ConnectThroughWebSocket,
            credentialsProvider: {
                get: {
                    credentials: () => ({
                        aws_access_key_id: credentials.accessKeyId,
                        aws_secret_access_key: credentials.secretAccessKey,
                        aws_session_token: credentials.sessionToken,
                    }),
                }
            },
            cleanSession: true,
            clientId: clientID,
            keepAlive: 30
        });

        // --- Event Listeners ---
        connection.on('connect', () => {
            console.log('Connected to AWS IoT Core!');
            connectionStatusElement.textContent = 'Connected';
            connectionStatusElement.style.color = 'green';

            // Subscribe to the topic
            connection.subscribe(MQTT_TOPIC, iot.QoS.AtLeastOnce)
                .then(() => {
                    console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
                })
                .catch(error => {
                    console.error('Subscription error:', error);
                    connectionStatusElement.textContent = `Connected (Subscription Failed)`;
                    connectionStatusElement.style.color = 'orange';
                });
        });

        connection.on('message', (topic, payload) => {
            console.log(`Message received on topic ${topic}: ${payload.toString()}`);
            try {
                const data = JSON.parse(payload.toString());
                iotDataElement.textContent = JSON.stringify(data, null, 2);
            } catch (e) {
                iotDataElement.textContent = `Raw: ${payload.toString()}`;
                console.warn('Received non-JSON message:', payload.toString());
            }
        });

        connection.on('error', (error) => {
            console.error('MQTT Connection Error:', error);
            connectionStatusElement.textContent = `Error: ${error.message}`;
            connectionStatusElement.style.color = 'red';
            reconnectButton.style.display = 'block';
        });

        connection.on('close', () => {
            console.log('MQTT Connection Closed');
            connectionStatusElement.textContent = 'Disconnected';
            connectionStatusElement.style.color = 'gray';
            reconnectButton.style.display = 'block';
        });

        // --- Connect to IoT Core ---
        await connection.connect();

    } catch (error) {
        console.error('Failed to connect to AWS IoT Core:', error);
        connectionStatusElement.textContent = `Failed to Connect: ${error.message || error}`;
        connectionStatusElement.style.color = 'red';
        reconnectButton.style.display = 'block';
    }
}

// --- Reconnect Button Handler ---
reconnectButton.addEventListener('click', () => {
    if (connection && connection.isConnected) {
        console.log('Already connected, no need to reconnect.');
        return;
    }
    connectAndSubscribe();
});

// --- Initial Connection on Page Load ---
document.addEventListener('DOMContentLoaded', connectAndSubscribe);

内容的提问来源于stack exchange,提问作者Ankit Vashisht

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:00:53