2016年1月15日金曜日

PubNub+Google Chart(Gauge)でセンサー・データを可視化する

  PubNubを使って、Arduinoで計測したセンサー・データ(温度)をブラウザで受信し、Google ChartのGauge(ゲージ)で可視化する方法を説明します。


①開発環境の構築
 「PubNubを使ってArudinoを制御する」の①~③の手順で開発環境を構築します。

②回路の配線
 次のように回路を配線します。



















③プログラムの作成
1.次のJavaScriptコードを入力し、「temp_pubnub.js」と名前を付けて、作業用フォルダに保存します。

var publishKey = '<your Publish Key>';
var subscribeKey = '<your Subscribe Key>';
var channel = "temperature"; // channel名の設定
var five = require("johnny-five");
var board = new five.Board({port: "COM3"});
board.on("ready", function() {
var temperature = new five.Thermometer({
controller: "LM35",
pin: "A0",
freq: 10000 // サンプリング間隔(ms)
});
// PubNub初期化
var pubnub = require("pubnub")({
ssl : true,
publish_key : publishKey,
subscribe_key : subscribeKey
});
temperature.on("data", function() {
console.log(this.celsius)
var data = {'value' : this.celsius};
// データの送信
pubnub.publish({
channel : channel,
message : data,
callback : function(message) {
console.log(message);
}
});
});
});
view raw temp_pubnub.js hosted with ❤ by GitHub
2.次のHTMLコードを入力し、「temp_pubnub.jhtml」と名前を付けて、任意の場所に保存します。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>温度</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://cdn.pubnub.com/pubnub.min.js"></script>
<script type="text/javascript">
var publishKey = 'pub-c-d1172091-ff3a-4e21-ba44-8ccff8959af3';
var subscribeKey = 'sub-c-c8f6cb7e-a505-11e5-a586-0619f8945a4f';
var channel2 = "temperature" // channel名の設定
// PubNub初期化
var pubnub = PUBNUB.init({
publish_key : publishKey,
subscribe_key : subscribeKey
});
// Google Chart
google.load("visualization", "1", {packages:["gauge", "line","corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Data for temperature Gauge
Data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temperature', 0],
]);
// Option for temperature Gauge
Options = {
width: 200, height: 200,
min: 0, max: 60,
redFrom: 50, redTo: 60,
yellowFrom:40, yellowTo: 50,
minorTicks: 5
};
Gauge = new google.visualization.Gauge(document.getElementById('temperatureGauge'));
Gauge.draw(Data, Options);
};
function subscribe() {
pubnub.subscribe({
channel : channel2
callback : function(data) {
console.log(data);
// Update temperature data
Data.setValue(0, 1, data.value);
Gauge.draw(Data, Options);
}
});
}
function unsubscribe(){
pubnub.unsubscribe({
channel : channel2
});
Data.setValue(0, 1, 0);
Gauge.draw(Data, Options);
}
</script>
</head>
<body>
<div>
<button onclick="subscribe()">接続</button>
<button onclick="unsubscribe()">切断</button>
</div>
<div id="temperatureGauge"></div>
</body>
</html>
<your Publish key>にはPublish Keyを、<your Subscribe key>にはSubscribe Keyを入力します。













④プログラムの実行と動作確認
1.コマンドプロンプトを起動し、作業用フォルダに移動します。
2.「node temp_pubnub.js」と入力します。
3.ブラウザで「ltemp_pubnub.html」を開いて、[接続]ボタンをクリックし、ゲージに温度が表示されることを確認します。
4.[切断]ボタンのクリックで、ゲージが0になることを確認します。


0 件のコメント:

コメントを投稿