(ほぼ)スマホ(だけ)を使ってIoTを始めてみよう～応用アプリを作る～

#概要
[「(ほぼ)スマホ(だけ)を使ってIoTを始めてみよう」](http://qiita.com/manamana/items/434cfc7ed6797851e2cc)の続きです
Node-REDのサンプルアプリをインポートして、IoTアプリをもう少し高度にしてみました。

//なんか意地になってスマホだけで操作しています。

// 20160616 datapalooza@秋葉原で紹介したデモアプリはここの手順で作れます。

// 201610 画面キャプチャを修正しました。

#背景(大事なことなので毎回言います）
面白そうな話を聞いて「へー、やってみたい」と思っても、家に帰って実際にやるかは気分次第。
気持ちが盛り上がっているうちに、スマホで！今すぐ！タダで！始めましょう。

#前提
* BluemixのIoTアプリを作っていること。まだの人は[ここ](http://qiita.com/manamana/items/434cfc7ed6797851e2cc)を実施してください
* Twillioの無料アカウントを作っていること（**+1で始まる米国番号をとってください**）まだの人は[https://www.twilio.com/try-twilio](https://www.twilio.com/try-twilio)とかから作成してください。

#用意するもの
* スマホ(センサーとして使います）
* BluemixアカウントとBluemix IoT アプリ
* Twillio電話番号（**+1 で始まる米国番号じゃないとだめ**）
* ガラケー(この電話番号をTwilioに登録。上記スマホと兼用でもOK）
* パソコン（複雑な操作とか実行結果の確認とか）

#全体の手順
1. サンプルコードをインポートする(スマホまたはパソコンで実施）
1. Twillioアカウント情報を設定する(スマホまたはパソコンで実施）
1. スマホをIoTセンサーに仕立てる（スマホでURLにアクセスするだけ）
1. スマホセンサー情報を流し込む（スマホまたはパソコンで実施）
1. スマホを振ってみる

#細かな手順
## サンプルコードをインポートする
1. 画面の三本線アイコンをクリックして、「Import」＞「Clipboard」を選択し、ダイアログ画面に以下のフロー（プログラム）をコピペします。
[ここ](http://qiita.com/egplnt/items/84b244a50d8bdaced324)にも詳しい手順があります。

フロー（プログラム）(datapaloozaで紹介したものです。)：

```
[{"id":"96a0694f.dbc0e8","type":"twilio-api","z":"dd7792a3.471f1","sid":"AC79edbcb542a2f88c8341493f625a9d7c","from":"+17201112222","name":"tel01"},{"id":"95f749e.26d6eb8","type":"ibmiot in","z":"dd7792a3.471f1","authentication":"quickstart","apiKey":"","inputType":"evt","deviceId":"465711112222","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT App In","service":"quickstart","allDevices":false,"allApplications":false,"allDeviceTypes":true,"allEvents":true,"allCommands":false,"allFormats":false,"x":140,"y":120,"wires":[["3a1b5143.5b8cbe"]]},{"id":"3a1b5143.5b8cbe","type":"function","z":"dd7792a3.471f1","name":"X方向の加速度を抽出","func":"return {payload:msg.payload.d.accelX};","outputs":1,"noerr":0,"x":360,"y":120,"wires":[["407819d.71c45e8"]]},{"id":"407819d.71c45e8","type":"function","z":"dd7792a3.471f1","name":"直近10件の情報に注目","func":"if ( !context.global.array ) {\n    context.global.array = new Array (10);\n}\nvar shifted = context.global.array.shift();\n\ncontext.global.array.push(msg.payload);\n\nmsg.array = context.global.array;\nmsg.length = context.global.array.length;\nreturn msg;","outputs":1,"noerr":0,"x":360,"y":180,"wires":[["783f89bb.be8348"]]},{"id":"783f89bb.be8348","type":"function","z":"dd7792a3.471f1","name":"移動平均","func":"var sum = 0, average = 0;\n    for (i=0; i<msg.length; i++) {\n        sum = sum + msg.array[i];\n}\nmsg.sum = sum;\naverage = sum / msg.length;\nmsg.average = average;\nreturn msg;\n","outputs":1,"noerr":0,"x":320,"y":240,"wires":[["89fb04c3.8b0e28"]]},{"id":"95789723.1e1978","type":"twilio out","z":"dd7792a3.471f1","service":"_ext_","twilio":"96a0694f.dbc0e8","from":"","number":"+818012345678","name":"保守担当者携帯にSMS","x":620,"y":300,"wires":[]},{"id":"4b2f8afe.d04f04","type":"comment","z":"dd7792a3.471f1","name":"センサーからのデータ受信","info":"","x":130,"y":60,"wires":[]},{"id":"6362539c.c0339c","type":"comment","z":"dd7792a3.471f1","name":"データ解析し異常振動を検知する","info":"","x":390,"y":60,"wires":[]},{"id":"8b94af1e.18b08","type":"comment","z":"dd7792a3.471f1","name":"解析結果の利用","info":"","x":620,"y":60,"wires":[]},{"id":"89fb04c3.8b0e28","type":"switch","z":"dd7792a3.471f1","name":"異常な振動が発生","property":"payload","propertyType":"msg","rules":[{"t":"gt","v":"100","vt":"str"}],"checkall":"true","outputs":1,"x":350,"y":300,"wires":[["95789723.1e1978"]]}]

```

こんなかんじ
![import01.png](https://qiita-image-store.s3.amazonaws.com/0/105029/28c8ef0c-d906-d9d4-b73b-2e2a95f53234.png)
![simple_flow.png](https://qiita-image-store.s3.amazonaws.com/0/105029/68a402ed-e28c-6012-bbe5-8776c0600f27.png)



## Twillioアカウント情報を設定する
1. Twillioにログインし、「Account SID」と「Auth Token」をメモする。
![twillio.png](https://qiita-image-store.s3.amazonaws.com/0/105029/b08bb638-54f9-295f-ac01-8079a1f8b938.png)

1. Node-REDのTwillioフローをダブルタップして、設定画面のTwillioID欄の鉛筆アイコンをタップする。
![simple_flow02.png](https://qiita-image-store.s3.amazonaws.com/0/105029/d5974048-7eb0-c725-0289-8c04238d83d2.png)

1. SMSの送信先電話番号を指定し、（Twillioトライアルの場合は申込時の電話番号のみ指定可能です）鉛筆アイコンを押す。
![twillio_auth.png](https://qiita-image-store.s3.amazonaws.com/0/105029/545f6b86-ba65-057f-8125-fb42e65a247c.png)


3. 認証情報に、1. の情報を設定して「Update」を押す
![twillio_token.png](https://qiita-image-store.s3.amazonaws.com/0/105029/eb974f87-105e-53ff-af98-a74df0cd8843.png)



## スマホをIoTセンサーに仕立てる
[ここ](http://qiita.com/manamana/items/434cfc7ed6797851e2cc#%E3%82%B9%E3%83%9E%E3%83%9B%E3%81%AE%E3%82%BB%E3%83%B3%E3%82%B5%E3%83%BC%E6%83%85%E5%A0%B1%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B)の手順と同じ。

1. スマートフォンで、ここにアクセス：http://phonesensor.mybluemix.net/
![QRcode_senser.gif](https://qiita-image-store.s3.amazonaws.com/0/71361/6cd2e618-d93f-845a-d968-415c3873cae1.gif)

1. スマホのセンサーIDをメモしておく
「d:quickstart:phone-sensor:[スマホのセンサーID]」
![sensor03.png](https://qiita-image-store.s3.amazonaws.com/0/71361/470084c8-26bc-fc26-f20d-120878538900.png)


## スマホの送ったセンサーデータをIoTアプリに流し込む
[ここ](http://qiita.com/manamana/items/434cfc7ed6797851e2cc#%E3%82%B9%E3%83%9E%E3%83%9B%E3%81%AE%E9%80%81%E3%81%A3%E3%81%9F%E3%82%BB%E3%83%B3%E3%82%B5%E3%83%BC%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92iot%E3%82%A2%E3%83%97%E3%83%AA%E3%81%AB%E6%B5%81%E3%81%97%E8%BE%BC%E3%82%80)の手順と同じ。


1. IoTアプリのURLにアクセスし、Node-REDのフロー編集画面を開きます。
「"アプリ名".mybluemix.net」

2. 青い入力フロー「IBM IoT App In」をダブルタップして、設定画面を開きます。設定画面のDeviceIDに、前項で確認したスマホのセンサーIDを記入し、OKを押して設定画面を閉じます。
![simple_flow03.png](https://qiita-image-store.s3.amazonaws.com/0/105029/3e56372c-5669-c943-0f90-ae0bf01294fe.png)
![flow_edit_device.png](https://qiita-image-store.s3.amazonaws.com/0/71361/c6ec800a-9106-dc64-1847-1b3f26c256b1.png)
 
3. フロー編集画面右上の「Deploy」 ボタンを押して、アプリケーションを更新します。
![simple_flow04.png](https://qiita-image-store.s3.amazonaws.com/0/105029/8ef5413c-f3a0-ee80-e3d8-27c7b10ee12a.png)


## 動かしてみる
スマホをガシガシ振ってみよう。


## 何も起こらなかったら？
黄色のノードをダブルタップすると、異常判定の閾値が変更できます。実機の振動レベルに合わせて調整してみましょう。
![simple_flow05.png](https://qiita-image-store.s3.amazonaws.com/0/105029/11dcfe48-2dc7-1738-e7ad-81b4be16f33d.png)


# もっと細かく挙動を見たい方はこっちのフローもどうぞ。
フロー（プログラム)

```
[{"id":"60232d75.006ac4","type":"twilio-api","z":"6d1fa5a.3378c5c","sid":"AC79edbcb542a2f88c8341493f625a9d7c","from":"+17201112222","name":"tel01"},{"id":"7849ddc3.9ca304","type":"ibmiot in","z":"6d1fa5a.3378c5c","authentication":"quickstart","apiKey":"","inputType":"evt","deviceId":"465711112222","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT App In","service":"quickstart","allDevices":false,"allApplications":false,"allDeviceTypes":true,"allEvents":true,"allCommands":false,"allFormats":false,"x":105,"y":123,"wires":[["606759e6.4430f8","e8117059.2ce46"]]},{"id":"e8117059.2ce46","type":"debug","z":"6d1fa5a.3378c5c","name":"device data","active":false,"console":"false","complete":"true","x":219,"y":187,"wires":[]},{"id":"606759e6.4430f8","type":"function","z":"6d1fa5a.3378c5c","name":"X方向の加速度を抽出","func":"return {payload:msg.payload.d.accelX};","outputs":1,"noerr":0,"x":344,"y":113,"wires":[["bf51b264.252"]]},{"id":"bf51b264.252","type":"function","z":"6d1fa5a.3378c5c","name":"直近10件の情報に注目","func":"if ( !context.global.array ) {\n    context.global.array = new Array (10);\n}\nvar shifted = context.global.array.shift();\n\ncontext.global.array.push(msg.payload);\n\nmsg.array = context.global.array;\nmsg.length = context.global.array.length;\nreturn msg;","outputs":1,"noerr":0,"x":451,"y":190,"wires":[["5c86e402.c695ec","289e5916.6eaf56"]]},{"id":"5c86e402.c695ec","type":"debug","z":"6d1fa5a.3378c5c","name":"","active":false,"console":"false","complete":"array","x":672,"y":190,"wires":[]},{"id":"289e5916.6eaf56","type":"function","z":"6d1fa5a.3378c5c","name":"移動平均","func":"var sum = 0, average = 0;\n    for (i=0; i<msg.length; i++) {\n        sum = sum + msg.array[i];\n}\nmsg.sum = sum;\naverage = sum / msg.length;\nmsg.average = average;\nreturn msg;\n","outputs":1,"noerr":0,"x":442,"y":247,"wires":[["61c9b961.c3b0f8","d4f3e455.6a7228","3e8d7ba7.8215d4"]]},{"id":"61c9b961.c3b0f8","type":"debug","z":"6d1fa5a.3378c5c","name":"","active":false,"console":"false","complete":"average","x":684,"y":248,"wires":[]},{"id":"d4f3e455.6a7228","type":"function","z":"6d1fa5a.3378c5c","name":"分散","func":"var variance = 0;\nfor (i=0; i<msg.length; i++) {\n    variance = variance + Math.pow(msg.array[i] - msg.average, 2);\n}\nvariance = variance / msg.length;\nmsg.variance = variance;\nreturn msg;\n","outputs":1,"noerr":0,"x":638,"y":307,"wires":[["1b44a62a.bf1cba","5316a80d.307dd8"]]},{"id":"1b44a62a.bf1cba","type":"debug","z":"6d1fa5a.3378c5c","name":"","active":false,"console":"false","complete":"variance","x":818,"y":308,"wires":[]},{"id":"5316a80d.307dd8","type":"function","z":"6d1fa5a.3378c5c","name":"標準偏差","func":"var standard_deviation = 0;\nstandard_deviation = Math.sqrt(msg.variance);\nmsg.std = standard_deviation;\nreturn msg;","outputs":1,"noerr":0,"x":648,"y":365,"wires":[["c6fe0020.0f524"]]},{"id":"c6fe0020.0f524","type":"debug","z":"6d1fa5a.3378c5c","name":"","active":false,"console":"false","complete":"std","x":798,"y":365,"wires":[]},{"id":"eb358ae8.2bc138","type":"twilio out","z":"6d1fa5a.3378c5c","service":"_ext_","twilio":"60232d75.006ac4","from":"","number":"+818012345678","name":"会社携帯にSMS","x":739,"y":591,"wires":[]},{"id":"8238ff41.450d8","type":"comment","z":"6d1fa5a.3378c5c","name":"センサーからのデータ受信","info":"","x":167,"y":69,"wires":[]},{"id":"73688c45.cc67e4","type":"comment","z":"6d1fa5a.3378c5c","name":"データ解析し振動を検知する","info":"","x":544,"y":72,"wires":[]},{"id":"8bc0c739.116ac8","type":"comment","z":"6d1fa5a.3378c5c","name":"解析結果の反映","info":"","x":734,"y":494,"wires":[]},{"id":"3e8d7ba7.8215d4","type":"switch","z":"6d1fa5a.3378c5c","name":"継続して振動が発生","property":"payload","propertyType":"msg","rules":[{"t":"gt","v":"30","vt":"str"}],"checkall":"true","outputs":1,"x":535,"y":486.5,"wires":[["8f282437.7aa858","eb358ae8.2bc138"]]},{"id":"8f282437.7aa858","type":"debug","z":"6d1fa5a.3378c5c","name":"","active":true,"console":"false","complete":"payload","x":730,"y":540,"wires":[]}]
```
![flow2_01.png](https://qiita-image-store.s3.amazonaws.com/0/105029/1e6f81da-51e8-fde7-c38d-0894e4ca442d.png)