【问题标题】:creating a web page that receives info from AWS IOT button创建一个从 AWS IOT 按钮接收信息的网页
【发布时间】:2018-08-09 14:22:44
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    你必须为 JS 安装 aws-sdk 和从 npm 安装 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。

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多