创建一个从AWS IOT按钮接收信息的网页

问题描述 投票:0回答:1

我想创建一个从AWS IOT按钮获取信息(MQTT消息)的网页。我有一个工作,配置按钮,我已经管理,使它发送MQTT信息到我的电脑。现在我希望这个MQTT信息显示在网页上。我希望网页计算请求的数量,并显示有关按钮的最新信息(在每个MQTT消息上)。我如何开始这个?我将不胜感激任何帮助。非常感谢。

node.js amazon-web-services http mqtt aws-iot
1个回答
0
投票

你必须从npm为JS和aws-sdk安装aws-iot-device-sdk。然后,你可以使用这样的东西:

import { CognitoIdentityCredentials, CognitoIdentity, config, Credentials } from "aws-sdk";
import { device } from "aws-iot-device-sdk";

const mqttClient = null;
config.region = "us-east-1";
config.credentials = new CognitoIdentityCredentials({
    IdentityPoolId: "us-east-1:your-pool-id",
});
config.getCredentials((err) => {
    if (err) console.log(err);
    else {
        const cId = new CognitoIdentity();
        cId.getCredentialsForIdentity({
            IdentityId: config.credentials.identityId
        })
            .promise()
            .then(result => {
                mqttClient = new device({
                    region: "us-east-1",
                    host: "your-iot-host.iot.us-east-1.amazonaws.com",
                    clientId: "any client id",
                    protocol: 'wss',
                    accessKeyId: result.Credentials.AccessKeyId,
                    secretKey: result.Credentials.SecretKey,
                    sessionToken: result.Credentials.SessionToken
                });
                mqttClient.on("connect", () => {
                    mqttClient.subscribe("some id for your web app - can be any string");
                });
                mqttClient.on("reconnect", () => {
                });
                mqttClient.on("message", (topic, payload) => {
                    console.log(String.fromCharCode.apply(null, payload));
                    const message = JSON.parse(String.fromCharCode.apply(null, payload));
                    console.log("message: " + message);
                });
            });
    }
});

请注意,上面的代码使用ES6功能。你可能不得不使用像babel这样的编译器将它转换为更多浏览器支持的ES5。

© www.soinside.com 2019 - 2024. All rights reserved.