9. AWS IoT Device SDK解説¶
本ハンズオンで利用したサンプルコードを元に、AWS IoT Device SDKの解説をします。
9.1. シナリオ1の解説¶
シナリオ1ではTopic(edison/illuminance)向けに照度センサーのデータをMQTTを利用してPublishします。
まず、証明書のパスを指定し、プライベート鍵、証明書、ルート証明書のパスを指定します。
1 2 3 4 5 6 7 | var device = awsIot.device({
keyPath: '../certs/privatekey.pem',
certPath: '../certs/cert.pem',
caPath: '../certs/rootca.crt',
clientId: 'eison_pub_client',
region: 'ap-northeast-1'
});
|
メッセージブローカに接続します。1秒ごとにループを回し、照度センサーからのデータ取得、メッセージの整形、メッセージのPublishを行います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | device.on('connect', function() {
console.log('Connected to Message Broker.');
setInterval(function() {
// Retrieve sensor data
var value = analogPin0.read();
// Display sensed analog data on LCD
myLCD.setColor(0, 255, 0);
myLCD.setCursor(0,0);
myLCD.write(clearStr);
myLCD.setCursor(0,0);
myLCD.write("DATA: " + value);
// Compose records
var record = {
"timestamp": moment().toISOString(), // ISO8601 format
"value": value
};
// Serialize record to JSON format and publish a message
var message = JSON.stringify(record);
console.log("Publish: " + message);
device.publish(topic, message);
}, 1000);
});
|
9.2. シナリオ2の解説¶
シナリオ2ではShadowのdeltaトピックに対しSubscribeおよびupdateトピックに対しPublishを行っています。
まず、証明書のパスを指定し、プライベート鍵、証明書、ルート証明書のパスを指定します。
1 2 3 4 5 6 7 | var thingShadows = awsIot.thingShadow({
keyPath: '/home/root/.node_app_slot/certs/privatekey.pem',
certPath: '/home/root/.node_app_slot/certs/cert.pem',
caPath: '/home/root/.node_app_slot/certs/rootca.crt',
clientId: 'edison_shadow_client',
region: 'ap-northeast-1'
});
|
メッセージブローカに接続します。
1 2 3 4 5 6 | thingShadows
.on('connect', function() {
console.log('connected to awsiot.');
thingShadows.register('edison');
clientTokenUpdate = thingShadows.update('edison', defaultState);
});
|
ステータスを監視します。
1 2 3 4 | thingShadows
.on('status', function(thingName, stat, clientToken, stateObject) {
console.log('received ' + stat + ' on ' + thingName + ': ' + JSON.stringify(stateObject));
});
|
アプリケーションからdesiredステータスのアップデートがあった場合、deltaのトピックにメッセージがpublishされます。deltaをsubscribeすることで変更をリアルタイムに受信します。
1 2 3 4 5 | thingShadows
.on('delta', function(thingName, stateObject) {
console.log('received delta '+' on ' + thingName + ': ' + JSON.stringify(stateObject));
updatedState = {"state":{"reported":{"led": ""}}};
});
|
ステータスをチェックし、デバイス内でそれぞれのステータスに応じた処理を実行します。
1 2 3 4 5 6 7 8 9 | if (stateObject.state.led == 'on') {
//ONの処理(LED点灯)
} else {
//OFFの処理(LED消灯)
}
|