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

时间:2018-03-01 13:44:08

标签: node.js amazon-web-services http mqtt aws-iot

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

1 个答案:

答案 0 :(得分: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。