上一篇中,我们非常简单地介绍了《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)); }); });