2015年12月24日木曜日

PubNubを使ってRaspberry Piを制御する

 内容的には、「PubNubを使ってArudinoを制御する」とほぼ同じです。

①PubNubのアカウントの登録(無料)
 PubNubに登録し、Publish KeyとSubscribe Keyを取得します。














②Raspberry Piのセットアップ
 「Raspberry Pi 2のGPIOをJavaScriptで制御する」の手順でRaspberry Piをセットアップします。

③PubNubモジュールのインストール
1.ターミナルを起動し、作業用フォルダに移動します。
2.「npm install pubnub」と入力します。

④コードの作成
1.次のJavaScriptコードを入力し、「main-pi.js」と名前を付けて作業用のフォルダに保存します。

var publishKey = '<your Publish Key>';
var subscribeKey = '<your Subscribe Key>';
var channel = "led-onoff"; // チャンネル名
var raspi = require('raspi-io');
var five = require('johnny-five');
var board = new five.Board({
io: new raspi()
});
board.on('ready', function(){
var led = new five.Led('P1-7');
// pubnub初期化
var pubnub = require("pubnub")({
ssl : true,
publish_key : publishKey,
subscribe_key : subscribeKey
});
// channel購読(データ受信)
pubnub.subscribe({
channel : channel,
callback : function(message){
console.log('>', message);
if(message.action === 'on'){
led.on();
} else {
led.off();
}
}
});
});
view raw main-pi.js hosted with ❤ by GitHub
2.次のHTMLコードを入力し、「index.html」と名前を付けて保存します。

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script src="https://cdn.pubnub.com/pubnub.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function(){
var publishKey = '<your Publish Key>';
var subscribeKey = '<your Subscribe Key>';
var channel = "led-onoff" // channel名の設定
// PubNub初期化
var pubnub = PUBNUB.init({
publish_key : publishKey,
subscribe_key : subscribeKey
});
// データの送信
function publish(action) {
var value = {'action': action};
pubnub.publish({
channel : channel,
message : value,
callback: function(message){
console.log(message);
}
});
}
// [ON]ボタンのクリックで文字列「on」を送信
$('#on-button').click(function(){
publish('on');
});
// [OFF]ボタンのクリックで文字列「off」を送信
$('#off-button').click(function(){
publish('off');
});
});
</script>
</head>
<body>
<button id="on-button">ON</button>
<button id="off-button">OFF</button>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
<your Publish key>には①のPublish Keyを、<your Subscribe key>には①のSubscribe Keyを入力します。

⑤動作の確認
1.ターミナルを起動し、作業用フォルダに移動します。
2.「sudo node main-pi.js」と入力します。
3.ブラウザで「index.html」を開き、[ON]ボタンのクリックでLED点灯、[OFF]ボタンのクリックでLEDが消灯することを確認します。

0 件のコメント:

コメントを投稿