3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【ラズパイIoT】node.jpを利用してhttpsとaws iotでslackに通知

3
Posted at

内容

ラズパイからhttpsとaws iotでslackのwebhookへ通知してみる
aws iot利用の場合はlambdaやSNSをどう用いてslackに通知が肝と思うけど、
とりあえず、リクエストするところだけ記載。

前提・環境

端末:ラズパイ3
$ uname -a
Linux raspberrypi 4.4.21-v7+ #911 SMP Thu Sep 15 14:22:38 BST 2016 armv7l GNU/Linux
$ node -v
v6.7.0

1.単純にHTTPリSクエスト

ライブラリとしてrequestを利用

git clone git@github.com:request/request.git
cd request
npm install

実際にリクエストするサンプルは下記

https.js
//requestをrequire
var request = require('request');

//ヘッダー
var headers = {
  'Content-Type':'application/json'
}
//オプションを定義
var options = {
  url: '<webhook-url>',
  method: 'POST',
  headers: headers,
  json: true,
  body: {"text":"fuga"}
}
//リクエスト送信
request(options, function (error, response, body) {
})

2.aws iotにpublish

aws iotに対して、publishを行う。
mqttのpublish先は"sample/iot"
awsコンソールでの設定等については省略。

aws iotのsdkはgithub
で結構詳しく記載しているからよく読めば大丈夫だと思うけど、参考として。

# 1つめはnpmから
npm install aws-iot-device-sdk
# 2つめはgithubから
git clone https://github.com/aws/aws-iot-device-sdk-js.git
cd aws-iot-device-sdk-js
npm install
awsiot_publish.jp
// AWS IoT DeviceSDKの利用
var awsIot = require('aws-iot-device-sdk');

// 秘密鍵、証明書などの設定
// certsディレクトリに一式置く。
var device = awsIot.device({
  region: '<your region>',
  clientId: '<your clientId>',
  privateKey: 'certs/private.pem.key',
  clientCert: 'certs/certificate.pem.crt',
  caCert: 'certs/root-CA.crt',
});

// 通信確立した際に呼び出されるイベント
device
  .on('connect', function() {
    console.log('connected');
      device.publish('sample/iot', JSON.stringify({ test_data: 'test message'}));
  });
device
  .on('message', function(topic, payload) {
    console.log('message', topic, payload.toString());
  });

// ちなみにconnectの中で呼ばれなくてもpublishは可能。
// 上記のpublishをコメントアウトしてこっち有効にしてもリクエストできる。
// device.publish('sample/iot', JSON.stringify({ test_data: 'test message'}));
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?