Blog

Blog

PHODAL

AWS IoT Node.js 开发物联网之MQTT——Hello,World

上一篇中,我们非常简单地介绍了《AWS IoT 开发物联网》,这篇简单地记录一下用Node.js结合AWS IoT开发物联网应用。

首先,你确认你已经有了AWS IoT账号。

然后安装AWS IoT Node.js SDK,当前版本是1.0.9

npm install aws-iot-device-sdk --save

接着,就是创建和运行

var awsIot = require('aws-iot-device-sdk');

var thingShadows = awsIot.thingShadow({
    keyPath: 'certs/fa635d3140-private.pem.key',
    certPath: 'certs/fa635d3140-certificate.pem.crt',
    caPath: 'certs/root-CA.crt',
    clientId: 'phodal',
    region: 'us-west-2'
});

thingShadows.on('connect', function () {
    console.log("Connected...");
    thingShadows.register('phodal');

    // An update right away causes a timeout error, so we wait about 2 seconds
    setTimeout(function () {
        console.log("Updating Led Status...");
        var led = thingShadows.update('phodal', {
            "state": {
                "reported": {
                    "led": false
                }
            }
        });
        console.log("Update:" + led);
    }, 2500);

});

这里,我们会在连接到AWS服务的时候,使用一个名为phodal的thing。

在这里要确保clientId和下面的phodal是一同一个变量,最好抽出一个变量名,如下:

var awsIot = require('aws-iot-device-sdk');

var thingName = 'Led';
var thingShadows = awsIot.thingShadow({
    keyPath: 'certs/fa635d3140-private.pem.key',
    certPath: 'certs/fa635d3140-certificate.pem.crt',
    caPath: 'certs/root-CA.crt',
    clientId: thingName,
    region: 'us-west-2'
});

thingShadows.on('connect', function () {
    console.log("Connected...");
    thingShadows.register(thingName);

    // An update right away causes a timeout error, so we wait about 2 seconds
    setTimeout(function () {
        console.log("Updating Led Status...");
        var led = thingShadows.update(thingName, {
            "state": {
                "reported": {
                    "led": true
                }
            }
        });
        console.log("Update:" + led);
    }, 2500);


    // Code below just logs messages for info/debugging
    thingShadows.on('status',
        function (thingName, stat, clientToken, stateObject) {
            console.log('received ' + stat + ' on ' + thingName + ': ' +
                JSON.stringify(stateObject));
        });

});

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签