AWS IoTを使って増えたRaspberry Piを手軽にシャットダウン

2019.05.28

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちはAIソリューション部のさかじです。 気がつくと身の回りにRaspberry Piが増えていませんか?増えたRaspberry Piを手軽にシャットダウンできる方法をツールを使わずAWS IoTのmqttのsubscribe機能を使う方法を試してみました。

環境

前提条件

Raspberry PiからAWS IoTへデータをmqttを使用して送信できている環境を使用してください。本ソースコードはエラー等考慮した作りになっていませんのでご注意ください。

Raspberry pi側ソースコード

app.js

'use strict'

const awsIot = require('aws-iot-device-sdk');
const deviceModele = awsIot.device;

const awsEnv = { 
    region: "ap-northeast-1",
    keyPath: "certs/private.pem.key",
    certPath: "certs/certificate.pem.crt",
    caPath: "certs/AmazonRootCA1.pem",
    host: "xxxxxxxx.iot.ap-northeast-1.amazonaws.com",
};

// 以下AWS IoT用起動時設定
const device = deviceModele({
    region: awsEnv.region,
    keyPath: awsEnv.keyPath,
    certPath: awsEnv.certPath,
    caPath: awsEnv.caPath,
    host: awsEnv.host 
});

// 通信確立した際に呼び出されるイベント
device.on('connect', function() {
  console.log("connect");
  device.subscribe('topic');
});

const childProcess = require('child_process');
// subscribeしたトピックにpublishされた時のイベント
device.on('message', function(topic, payload) {
  console.log('message', topic, payload.toString());
  const jsonData = JSON.parse(payload.toString('utf-8'));
  if (jsonData.command == 'halt') {
    console.log('RasPi halt');
    childProcess.exec('sudo halt');
  }
});

Raspberry Piのアプリケーション起動

$ sudo node app.js

AWS IoT マネジメントコンソール

"AWS IoT" - "テスト" - "発行"で下記のように入力して"トピックに発行"をクリックします。

しばらくするとRaspberry Piが終了して電源切れる状態になります。

参考サイト

最後に

非常に簡単かつ雑に作ってみました。今回はAWS IoTのコンソールから直接発行しましたが、シャットダウンボタンを作って AWS IoTへシャットダウン情報をPublishして関連するRaspberry Piをシャットダウンさせる方法もできると思います。