在一些关于物联网的文章的时候,发现有必要写一下怎么使用AWS IoT。如果你也有AWS帐号的话,也可以试试。
这里假设你已经可以进入创建资源页了。
创建资源
在最这里,我们可以看到我们已经创建好的资源,如下图所示:
我们只需要点击上面的Create a resource就可以创建一个相关的资源,我们所需要做的就是填一个名字,如phodal。
随后,点击某个资源后,我们可以查看这个资源的相关信息:
上面会有这个API的RESET API,以及MQTT Topic。每次当我们更新内容的时候,相关的订阅者就可以收到更新。
AWS IoT MQTT
网上找了一个相关的MQTT示例,我们所需要做的就是订阅相关的topic,部分代码如下所示:
mqttc.tls_set("./certs/root-CA.crt",
certfile="./certs/fa635d3140-certificate.pem.crt",
keyfile="./certs/fa635d3140-private.pem.key",
tls_version=ssl.PROTOCOL_TLSv1_2,
ciphers=None)
mqttc.connect("a1dul237m8y7r3.iot.us-west-2.amazonaws.com", port=8883) # AWS IoT service hostname and portno
mqttc.subscribe("$aws/things/phodal/shadow/update/#",
qos=1) # The names of these topics start with $aws/things/thingName/shadow."
随后,运行这个脚本,当我们更新shadow(可以在服务端)更新的时候,我们就可以接收到相关的更新:
Received message from topic: $aws/things/phodal/shadow/update/accepted | QoS: 0 | Data Received: {"state":{"reported":{"led":true},"desired":{}},"metadata":{"reported":{"led":{"timestamp":1449146881}},"desired":{}},"version":2,"timestamp":1449146881}
Node.js
首先,我们需要安装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));
});
});
或许您还需要下面的文章: