この投稿は Electric Imp Advent Calendar 2015 の10日目の記事です。
タクトスイッチを使った回路
前回の「タクトスイッチの入力を読み取る」の回路と同じものを使います。
今回は回路はそのままに、タクトスイッチを押した時にLEDのON/OFFではなく、前々回に紹介したTwilioを利用してみましょう。
前々回の記事はこちらです。
今回は、ElectricImpからTwilioを利用できるライブラリを使って、タクトスイッチが押されたら携帯電話にSMSを送るデバイスを作ってみます。
デバイスのコードを書く
#require "Button.class.nut:1.1.0" led <- hardware.pin9; led.configure(DIGITAL_OUT, 0); button <- Button(hardware.pin7, DIGITAL_IN_PULLDOWN, Button.NORMALLY_LOW); state <- 0; button.onPress(function() { server.log("Button pressed"); state = 1 - state; led.write(state); agent.send("sms.send", "こんにちは!こんにちは!!"); }); button.onRelease(function() { server.log("Button released"); });
前回のコードに以下の行を追加しました。
agent.send("sms.send", "こんにちは!こんにちは!!");
ElectricImpからTwilioのAPIを叩くライブラリはエージェントでしか利用できないので、デバイスのボタンがおされたことをエージェントに通知します。
第一引数にSMSで送信したいメッセージを渡しています。
エージェントのコードを書く
#require "Twilio.class.nut:1.0.0" accountSID <- "xxxxx"; authToken <- "xxxxx"; twilioNumber <- "+1xxxxx"; recipientsNumber <- "+81xxxxx"; twilio <- Twilio(accountSID, authToken, twilioNumber); function sendMessage(message){ twilio.send(recipientsNumber, message, function(response) { server.log("twilio sent: " + response.statuscode + " - " + response.body); }); } device.on("sms.send", sendMessage);
accountSID <- "xxxxx"; authToken <- "xxxxx"; twilioNumber <- "+1xxxxx"; recipientsNumber <- "+81xxxxx";
accountSID
と authToken
はTwilioの管理画面からAPIクレデンシャルを確認して設定します。
twilioNumber
はTwilioの管理画面から取得した電話番号です。 recipientsNumber
はSMSの送信先の電話番号です。(Twilioをトライアルで利用している場合は、認証済みの電話番号のみ送信先に利用できます。)
function sendMessage(message){ twilio.send(recipientsNumber, message, function(response) { server.log("twilio sent: " + response.statuscode + " - " + response.body); }); }
twilio.send
でSMSを送信できます。第三引数のコールバック関数を指定しないとこの関数呼び出しはブロックされ、コールバック関数を指定すると非同期に処理されます。
実際に送ってみる
ビルドしてImpにデプロイします。
タクトスイッチを押すと、以下のようなSMSが送信されました!
Impのログは以下のように出力されました。
2015-12-15 00:04:57 UTC+9 [Status] Agent restarted: reload. 2015-12-15 00:04:57 UTC+9 [Status] Device connected 2015-12-15 00:05:06 UTC+9 [Device] Button pressed 2015-12-15 00:05:06 UTC+9 [Device] Button released 2015-12-15 00:05:07 UTC+9 [Agent] twilio sent: 201 - {"sid": "xxxxx", "date_created": "Mon, 14 Dec 2015 15:05:07 +0000", "date_updated": "Mon, 14 Dec 2015 15:05:07 +0000", "date_sent": null, "account_sid": "xxxxx", "to": "+81xxxxx", "from": "+1xxxxx", "body": "\u3053\u3093\u306b\u3061\u306f\uff01\u3053\u3093\u306b\u3061\u306f\uff01\uff01", "status": "queued", "dir[...truncated...]
簡単ですね!環境センサーの値を監視して条件を満たしたらSMSで通知みたいなことがお手軽に実現できます!