3
3

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.

Watson IoT Platform - サンプルフロー - DBからのIoTデータを表示

Last updated at Posted at 2016-08-16

このサンプルのフローでは、dashDBに保存されたIoTデータをD3.jsを使用して可視化します。
dashDBの準備については、Watson IoT Platform - 直接dashDBへデータを格納するなどをご参照ください。

#サンプル1:センサーからのIoTデータをリアルタイムで表示する

  1. Node-REDのフローをコピーする方法を参照して、下記のフローをコピペします。
  2. 「入力用画面を返す」ノードを開き、22行目の <form action="http://このIoTアプリの名前.mybluemix.net/test43の「このIoTアプリの名前」を使用しているNode-REDアプリの名前に更新し、画面右上の赤い「Deploy」ボタンを押します
  3. 「DBからデータを取得」ノードを開き、使用している(SENSOR2DBデータベースにCC2650のデータが保存されている)dashDBインスタンスが正しく選択されていることを確認します
  4. ブラウザを開きアプリ名.mybluemix.net/test42へアクセスします
  5. 表示対象の属性名と表示期間を指定し、「送信」を押します
dashDBからのIoTデータを表示
[{"id":"2eb6a12a.6ef6e6","type":"dashDB in","z":"b9820341.436a5","service":"dashDB-gw","query":"select * from SENSOR2DB \nwhere month between ? and ?\nand\nday between ? and ? \nand \nhour between ? and ?\nand \nminute between ? and ?\norder by month, day, hour, minute;","params":"msg.startmonth,msg.endmonth,msg.startday,msg.endday,msg.starthour,msg.endhour,msg.startminute,msg.endminute","name":"DBからデータを取得","x":500,"y":260,"wires":[["3fecad0f.fb3d32"]]},{"id":"3fecad0f.fb3d32","type":"function","z":"b9820341.436a5","name":"stringify","func":"var m = JSON.stringify(msg.payload);\nmsg.payload.op = m;\nvar n = JSON.stringify(msg.targetattr);\nmsg.payload.targetattr = n;\nreturn msg;","outputs":1,"noerr":0,"x":300,"y":320,"wires":[["10facdf7.cecfa2"]]},{"id":"10facdf7.cecfa2","type":"template","z":"b9820341.436a5","name":"グラフを表示","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n  <meta charset=\"utf-8\">\n  <title>データベースからのIoTデータ表示</title>\n  <script src=\"https://d3js.org/d3.v4.min.js\"></script>\n\n  <style type=\"text/css\">\n  /* ここにスタイルルールを追加します */\n  .axis path,\n  .axis line {\n    fill: none;\n    stroke: black;\n    shape-rendering: crispEdges;\n  }\n  .axis text {\n    font-family: Meiryo;\n    font-size: 11px;\n  }\n  </style>\n\n  <div id=\"op\" foo={{ payload.op }}/>\n  <div id=\"ta_a\" ta_b={{ payload.targetattr }}/>\n\n  <script type=\"text/javascript\">\n  //  payload.opにdashDB検索結果を、payload.targetattrに表示対象の属性名を保持\n  var ta_c = document.getElementById( 'ta_a' ).getAttribute( 'ta_b' );\t//属性名を取得\n  target_attr = ta_c.substr( 1, ta_c.length-3 );  //冒頭と末尾の\"\"を削除。エラーになるので。\n\n  var op_a = document.getElementById( 'op' ).getAttribute( 'foo' );\t//検索結果を取得\n  op_a = op_a.substr( 0, op_a.length-1 ) ;\t//末尾の\"/\"でエラーになるので\n  var op_a2 = JSON.parse(op_a);\t//JSON文字列からjavascriptオブジェクトを復元\n\n  var op_a3 = new Array();\n  for(var i in op_a2){\n    op_a3.push(op_a2[i][target_attr]);\t//対象とする属性の値を取り出して配列op_a3に順次格納\n  }\n\n  var op_a5 = new Array();\n  for(var i in op_a2){        // 対象エントリーの時刻を格納\n    op_a5.push(op_a2[i].HOUR + \":\" + (( \"0\" + op_a2[i].MINUTE ).substr( -2 )));\n  }\n\n  var m =  0;   //  時と分を結合して時刻を保持する\n  var mh = 0;   //  最大値が発生したときの時\n  var mm = 0;   //  最大値が発生したときの分\n  var mt = 0;   //  最大値\n  for(var i in op_a2){\n    //  console.log('i = ', i, ', value = ', op_a2[i][target_attr], ', h = ', op_a2[i].HOUR, ', m = ', op_a2[i].MINUTE);\n    //  op_a2配列を探索して、最大値を見つける\n    if (m < Number(op_a2[i][target_attr])) {\n      m = Number(op_a2[i][target_attr]);\n      mh = op_a2[i].HOUR;\n      mm = ( \"0\" + op_a2[i].MINUTE ).substr( -2 ) ;\n      mt = op_a2[i][target_attr];      // 最大値の文字列での値\n      mv = parseFloat(mt, 10);         // 最大値の数値での値\n      //console.log(\"max found was \" + mh + \":\" + mm + \" \" + mt);\n    }\n  }\n\n  m = mh + \":\" + mm;\n  //  console.log('mt = ', mt);\n  // 表示する画面の幅( Width )と高さ( height )\n  var w = 1000;\n  //  zoomの値は、最大値が100以上であればそのまま(1倍)、最大値が100より小さければ4倍、\n  // 最大値が10より小さければ10倍、最大値が3より小さければ20倍に\n  var zoom = ( mv < 100 ) ? (( mv < 10 ) ? (( mv < 3 ) ? 20 : 10 ) : 4 ) : 1;\n  //  console.log('zoom = ', zoom);\n  //  画面の高さは、最大値xズーム値+50 か 100のどちらか大きいほう\n  var h = Math.max(mv*zoom + 50, 100);\n  //  console.log('h = ', h);\n  var barPadding = 1;  // 棒グラフの棒と棒の間隔\n  var margin = 30;     // グラフ表示域のまわりの余白\n\n  var dataset = op_a3;    //  対象エントリーを保持\n  var datasetT = op_a5;   //  対象エントリーの時刻を保持\n\n  // スケール関数の生成\n  var xScale = d3.scaleLinear()\n    .domain([0, d3.max(dataset, function(d) { return d; })])\n    .range([margin, w + margin * 2]);\n\n  var yScale = d3.scaleLinear()\n    .domain([0, (h-margin) / zoom]) // Y軸のスケールを棒グラフと一致させる\n    .range([h-margin, 0]);    // Y軸表示場所\n\n  // X 軸の定義\n  var xAxis = d3.axisBottom()\n    .scale(xScale);\n\n  // Y 軸の定義\n  var yAxis = d3.axisLeft(yScale);\n\n  // SVG 要素の生成\n  var canvas = d3.select(\"body\")\n    .append(\"svg\")\n    .attr(\"width\", w)\n    .attr(\"height\", h);\n\n  canvas.selectAll(\"rect\")\n    .data(dataset)\n    .enter()\n    .append(\"rect\")\n    .attr(\"x\", function(d, i) {\n      return i * ((w-margin) / dataset.length) + margin;\n    })\n    .attr(\"y\", function(d) {    //  負の値は絶対値で対応\n      return h - (Math.abs(d) * zoom) - margin;\n    })\n    .attr(\"width\", (w-margin) / dataset.length - barPadding)\n    .attr(\"height\", function(d) {\n      return Math.abs(d) * zoom;      //  負の値は絶対値で対応\n    })\n    .attr(\"fill\", function(d) {\n      //return \"rgb(100, 100, \" + (d * 10) + \")\";\n      return \"rgb(224, 194, 132)\";    //  杏色\n  });\n\n  canvas.selectAll(\"text\")\n    .data(datasetT)\n    .enter()\n    .append(\"text\")\n    .text(function(d) {\n      return d;\n    })\n    .attr(\"text-anchor\", \"middle\")\n    .attr(\"x\", function(d, i) {\n      return i * ((w-margin) / dataset.length) + margin + ((w-margin) / dataset.length - barPadding ) / 2;\n    })\n    .attr(\"y\", function(d) {\n      return h;\n    })\n    .attr(\"font-family\", \"Meiryo\")\n    .attr(\"font-size\", \"11px\")\n    .attr(\"fill\", \"black\");\n\n// X 軸の生成\n/*canvas.append(\"g\")\n    .attr(\"class\", \"axisBottom\")\n    .attr(\"transform\", \"translate(0,\" + (h - margin) + \")\")\n    .call(xAxis);\n*/\n// Y 軸の生成\ncanvas.append(\"g\")\n    .attr(\"class\", \"axisLeft\")\n    .attr(\"transform\", \"translate(\" + margin + \",0)\")\n    .call(yAxis);\n\n\nwindow.onload = function onLoad() {\n  var target1 = document.getElementById(\"output1\");     //  表示対象の属性名\n  target1.innerHTML = target_attr;\n  var target2 = document.getElementById(\"output2\");     //  最高値の時刻\n  target2.innerHTML = m;\n  var target3 = document.getElementById(\"output3\");     //  最高値\n  target3.innerHTML = mt;      // 最大値をロード\n}\n\n</script>\n</head>\n<body>\n\n  <div id=\"a-box\" style=\"background-color: #87cefa; padding: 20px; font-family: Meiryo;\">\n    <h1>データベースからのIoTデータ表示</h1>\n    <br />\n    <p>\n      データベースに保存されたIoTデータを可視化します(加速度などのマイナス値は絶対値で表示しています)\n      <br />\n    </p>\n  </div>\n\n  <div id=\"b-box\" style=\"background-color: #ecf2fe; padding: 20px; font-family: Meiryo; \">\n    <div style=\"text-align:left\" id=\"output0\"></div>\n    <h2>\n      <span style=\"text-align:left; font-size:18pt; color:blue\" id=\"output1\"></span> 値の出力\n    </h2>\n    <h2>最高値の時刻</h2>\n      <span style=\"text-align:left; font-size:18pt; color:blue\" id=\"output2\"></span>\n    <h2>最高値 </h2>\n      <span style=\"text-align:left; font-size:18pt; color:blue\" id=\"output3\"></span>\n  </div>\n</body>\n</html>\n","x":480,"y":320,"wires":[["bfa2ef08.c01b88"]]},{"id":"bfa2ef08.c01b88","type":"http response","z":"b9820341.436a5","name":"","x":670,"y":320,"wires":[]},{"id":"aae95e90.86278","type":"http in","z":"b9820341.436a5","name":"","url":"/test42","method":"get","swaggerDoc":"","x":130,"y":120,"wires":[["3dd30a64.5a7b4e"]]},{"id":"e2fb681.3b9ad98","type":"http response","z":"b9820341.436a5","name":"","x":510,"y":120,"wires":[]},{"id":"3dd30a64.5a7b4e","type":"template","z":"b9820341.436a5","name":"入力用画面を返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>IoT Quick Dashboard</title>\n\t\t<meta charset=\"utf-8\" />\n\t</head>\n\t<body>\n\n<div id=\"a-box\" style=\"background-color: #96e0a9; padding: 20px; font-family: Meiryo;\">\n\n\t<h1>IoT Quick Dashboard</h1>\n\t<br />\n\t<p>\n\t\tdashDBに保存されたIoTデータを可視化します<br />\n\t</p>\n</div>\n\n<div id=\"b-box\" style=\"background-color: #ecf2fe; padding: 20px; font-family: Meiryo; \">\n\n    <H2>入力!</H2>\n  <P>表示対象の属性と期間を指定します。</P>\n  <form action=\"http://このIoTアプリの名前.mybluemix.net/test43\" method=\"get\">\n\t\t<select name=\"targetattr\">\n\t\t    <option>AMBIENTTEMP</option>\n\t\t\t\t<option>ACCELX</option>\n\t\t\t\t<option>ACCELY</option>\n\t\t\t\t<option>ACCELZ</option>\n\t\t\t\t<option>GYROX</option>\n\t\t\t\t<option>GYROY</option>\n\t\t\t\t<option>GYROZ</option>\n\t\t\t\t<option>HUMIDITY</option>\n\t\t\t\t<option>LIGHT</option>\n\t\t\t\t<option>MAGX</option>\n\t\t\t\t<option>MAGY</option>\n\t\t\t\t<option>MAGZ</option>\n\t\t    <option>OBJECTTEMP</option>\n\t\t  </select><br><br>\n      この日時から<input type=\"datetime-local\" name=\"starttime\" value=\"2016-11-8T17:21:00\" step=\"60\">\n      この日時まで<input type=\"datetime-local\" name=\"endtime\" value=\"2012-11-8T17:21:00\" step=\"60\"><br><br>\n  <INPUT type=\"submit\" value=\"送信\"><BR>\n  <INPUT type=\"reset\" value=\"リセット\"><BR><BR>\n  </FORM>\n\n</div>\n\n<div id=\"c-box\" style=\"background-color: #f0e8fa; padding: 20px; font-family: Meiryo; \">\n\t<br />\n\t<div class=\"category\"><h3>関連リンク</h3></div>\n\t\t<ul>\n\t\t\t<li><a href=\"http://qiita.com/egplnt/items/af867711a7191923b2ff\">Qiita: Watson IoT Platformを使ってみる</a></li>\n\t\t\t<li><a href=\"https://internetofthings.ibmcloud.com/#/\">IBM Watson IoT Platform</a></li>\n\t\t\t<li><a href=\"https://bluemix.net\">Bluemix</a></li>\n\t\t\t<li><a href=\"https://developer.ibm.com/recipes/tutorials/use-the-simulated-device-to-experience-the-iot-foundation/\">Recipe - Simulator</a></li>\n\t\t</ul>\n\t<div class=\"category\"><h3>資料ページ</h3></div>\n\t\t<ul>\n\t\t\t<li><a href=\"http://ibm.com/iot\">IBM IoT</a></li>\n\t\t\t<li><a href=\"https://docs.internetofthings.ibmcloud.com/ja/\">Watson IoT Platform資料ページ</a></li>\n\t\t\t<li><a href=\"https://developer.ibm.com/recipes/\">Recipe</a></li>\n\t\t</ul>\n</div>\n\n<div id=\"d-box\" style=\"clear: both; background-color: #e0ce96; font-size: 18px; padding: 10px; text-align: center;  padding: 20px; font-family: Meiryo;\">\n\t\tcopyright (c) abc.com All right reserved.\n</div>\n\t</body>\n</html>\n","x":330,"y":120,"wires":[["e2fb681.3b9ad98"]]},{"id":"ffa6e27d.bffc98","type":"http in","z":"b9820341.436a5","name":"","url":"/test43","method":"get","swaggerDoc":"","x":130,"y":260,"wires":[["882885a3.f23b4"]]},{"id":"c34b1569.a2526","type":"comment","z":"b9820341.436a5","name":"DBから値を取得し表示","info":"","x":140,"y":220,"wires":[]},{"id":"882885a3.f23b4","type":"function","z":"b9820341.436a5","name":"値を取得","func":"msg.startmonth = msg.payload.starttime.substr(5,2);\nmsg.startday = msg.payload.starttime.substr(8,2);\nmsg.starthour = msg.payload.starttime.substr(11,2);\nmsg.startminute = msg.payload.starttime.substr(14,2);\n\nmsg.endmonth = msg.payload.endtime.substr(5,2);\nmsg.endday = msg.payload.endtime.substr(8,2);\nmsg.endhour = msg.payload.endtime.substr(11,2);\nmsg.endminute = msg.payload.endtime.substr(14,2);\n\nmsg.targetattr = msg.payload.targetattr;\n\nreturn msg;","outputs":1,"noerr":0,"x":300,"y":260,"wires":[["2eb6a12a.6ef6e6"]]},{"id":"cdba37a9.e3b2d","type":"comment","z":"b9820341.436a5","name":"表示する属性と期間を指定","info":"","x":150,"y":80,"wires":[]}]

スクリーンショット 2016-11-09 13.33.03.png
スクリーンショット 2016-11-09 13.33.14.png
スクリーンショット 2016-11-09 13.33.40.png

#サンプル2:センサータグ(CC2650)からのIoTデータを指定した間隔でdashDBへ書き込む
下記のフローではセンサータグCC2650からのIoTデータを指定した間隔でdashDBへ書き込み、それを表示します。

  1. センサータグCC2650からデータを取得します
  2. 指定した間隔でdashDBへ直接書き込みます
  3. 必要に応じ、「センサー値を出力」functionノードを開き、冒頭のインターバル値を調整します。

スクリーンショット 2016-08-17 13.21.37.png

センサータグCC2650からのデータをdashDBへ格納し、D3で可視化する
[{"id":"175917e8.30b87","type":"inject","z":"64589e61.60898","name":"1秒毎","topic":"","payload":"","payloadType":"date","repeat":"1","crontab":"","once":false,"x":110,"y":200,"wires":[[]]},{"id":"c3e41b5d.223d28","type":"inject","z":"64589e61.60898","name":"restart","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"x":110,"y":240,"wires":[[]]},{"id":"a0155b1b.cda098","type":"comment","z":"64589e61.60898","name":"IoTデータを指定した間隔でDBへ書き込み","info":"","x":200,"y":60,"wires":[]},{"id":"6d18f085.c1b5d8","type":"function","z":"64589e61.60898","name":"日付時刻の追加","func":"var d = new Date();\nvar localTime = d.getTime();\nvar localOffset = d.getTimezoneOffset() * 60000;\nvar utc = localTime + localOffset;\nvar offset = -9.0;\nvar result = utc - (3600000 * offset);\nvar date = parseInt(new Date(result) / 1000);\nvar dt = new Date(result);\n\nvar year = dt.getFullYear();\nvar month = dt.getMonth()+1;\nvar day = dt.getDate();\nvar hour = dt.getHours();\nvar minute = dt.getMinutes();\nvar second = dt.getSeconds();\n//if (!msg.payload) {\n//    msg.payload = { \"initial\": \"value\" };\n//}\nif (!msg.date) {\n    msg.date = { \"initial\": \"value\" };\n}\nmsg.date = {\n        \"date\": date,\n        \"year\": year,\n        \"month\": month,\n        \"day\": day,\n        \"hour\": hour,\n        \"minute\": minute,\n        \"second\": second\n};\nreturn msg;","outputs":1,"noerr":0,"x":301,"y":140,"wires":[["3b7f6362.24696c","def4328.f99acd"]]},{"id":"3b7f6362.24696c","type":"debug","z":"64589e61.60898","name":"時刻の表示","active":false,"console":"false","complete":"date","x":510,"y":100,"wires":[]},{"id":"14d3087b.28646","type":"function","z":"64589e61.60898","name":"表へ書き込む","func":"msg.payload = \n{ \n\tDATE : msg.date.date,\n\tDAY : msg.date.day,\n\tHOUR : msg.date.hour,\n\tMINUTE : msg.date.minute,\n\tMONTH : msg.date.month,\n\tSECOND : msg.date.second,\n\tYEAR : msg.date.year,\n\tACCELX : msg.sensor.accelX,\n\tACCELY : msg.sensor.accelY,\n\tACCELZ : msg.sensor.accelZ,\n\tAMBIENTTEMP : msg.sensor.ambientTemp,\n\tGYROX : msg.sensor.gyroX,\n\tGYROY : msg.sensor.gyroY,\n\tGYROZ : msg.sensor.gyroZ,\n\tHUMIDITY : msg.sensor.humidity,\n\tLIGHT : msg.sensor.light,\n    MAGX : msg.sensor.magX,\n\tMAGY :msg.sensor.magY,\n\tMAGZ : msg.sensor.magZ,\n\tOBJECTTEMP : msg.sensor.objectTemp\n};\n\nreturn msg;\n","outputs":1,"noerr":0,"x":520,"y":220,"wires":[["ba9d26f1.6a516","ecfd037.e72c4"]]},{"id":"8bcc302e.8dbd58","type":"function","z":"64589e61.60898","name":"センサー値を出力","func":"var sampling_min_interval = 10;     // 10分毎にDBヘ書き込み\nvar sampling_sec_interval = 60;     // データを出力する間隔\n\n/*\nvar sum = 0, average = 0;\nvar sen1 = Math.floor(Math.random () * 10) + 1; // センサー値を生成(シミュレート)\n\nif ( !context.array ) {\n    context.array = new Array (10); //直近10件分を保持\n}\nvar shifted = context.array.shift();\ncontext.array.push(sen1);           // 最新の値を保存\nvar length = context.array.length;\n\nfor (k=0; k<length; k++) {\n        sum = sum + context.array[k];   // 合計を算出\n}\n\nvar hour = JSON.stringify(msg.date.hour);\nvar min_org  = JSON.stringify(msg.date.minute);\nvar min = ( \"0\" + min_org ).substr( -2 );       // 一桁分の場合、二桁に\nvar sec_org  = JSON.stringify(msg.date.second);\nvar sec = ( \"0\" + sec_org ).substr( -2 );       // 一桁秒の場合、二桁に\nvar time = hour + \":\" + min + \":\" + sec;\n\naverage = sum / length;\nvar data = [[time],[sen1],[average]];\nmsg.sensor.average = average;\n*/\nif ( ( msg.date.second % sampling_sec_interval ) !== 0 ) return;\nif ( ( msg.date.minute % sampling_min_interval ) !== 0 ) return;\nreturn msg;\n","outputs":1,"noerr":0,"x":310,"y":220,"wires":[["14d3087b.28646"]]},{"id":"b7faf05f.7d756","type":"ibmiot in","z":"64589e61.60898","authentication":"quickstart","apiKey":"","inputType":"evt","deviceId":"","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT","service":"quickstart","allDevices":"","allApplications":"","allDeviceTypes":true,"allEvents":true,"allCommands":"","allFormats":"","x":90,"y":140,"wires":[["6d18f085.c1b5d8"]]},{"id":"4144253.9dd2fdc","type":"http in","z":"64589e61.60898","name":"","url":"/test28","method":"get","swaggerDoc":"","x":110,"y":380,"wires":[["1f8c6452.0e2c14"]]},{"id":"fdd5ab25.ad1cd8","type":"debug","z":"64589e61.60898","name":"op","active":false,"console":"false","complete":"payload.op","x":670,"y":360,"wires":[]},{"id":"d1c0278d.5bf49","type":"template","z":"64589e61.60898","name":"htmlを返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n   <meta charset=\"utf-8\">\n   <title>データベースからのIoTデータ表示</title>\n      <script src=\"https://d3js.org/d3.v4.min.js\"></script>\n\n   <style type=\"text/css\">\n         /* ここにスタイルルールを追加します */\n      .axis path,\n      .axis line {\n         fill: none;\n         stroke: black;\n         shape-rendering: crispEdges;\n      }\n      .axis text {\n         font-family: sans-serif;\n         font-size: 11px;\n      }\n   </style>\n\n   <div id=\"op\" foo={{payload.op}}/>\n\n<script type=\"text/javascript\">\n\nvar op_a = document.getElementById( 'op' ).getAttribute( 'foo' );\t//データを取得\nop_a = op_a.substr( 0, op_a.length-1 ) ;\t//末尾の\"/\"でエラーになるので\nvar op_a2 = JSON.parse(op_a);\t//JSON文字列からjavascriptオブジェクトを復元\n\nvar op_a3 = new Array();\nfor(var i in op_a2){\n\top_a3.push(op_a2[i].AMBIENTTEMP);\t//AMBIENTTEMPを取り出して配列op_a3に順次格納\n}\n\nvar op_a5 = new Array();\nfor(var i in op_a2){\n\top_a5.push(op_a2[i].HOUR + \":\" + (( \"0\" + op_a2[i].MINUTE ).substr( -2 )));\n}\n\n   // 幅( Width )と高さ( height )\n   var w = 800;\n   var h = 300;\n   var zoom =5;\n   var barPadding = 1;  // 棒グラフの棒と棒の間隔\n   var margin = 30;     // グラフ表示域のまわりの余白\n   \n   var dataset = op_a3;\n   var datasetT = op_a5;\n   \n   // スケール関数の生成\n   var xScale = d3.scaleLinear()\n         .domain([0, d3.max(dataset, function(d) { return d; })])\n         .range([margin, w + margin * 2]);\n\n   var yScale = d3.scaleLinear()\n            .domain([0, (h-margin) / zoom]) // Y軸のスケールを棒グラフと一致させる\n            .range([h-margin, 0]);    // Y軸表示場所\n\n   // X 軸の定義\n   var xAxis = d3.axisBottom()\n        .scale(xScale);\n\n   // Y 軸の定義\n   var yAxis = d3.axisLeft(yScale);\n   \n   // SVG 要素の生成\n   var canvas = d3.select(\"body\")\n         .append(\"svg\")\n         .attr(\"width\", w)\n         .attr(\"height\", h);\n\n   canvas.selectAll(\"rect\")\n         .data(dataset)\n         .enter()\n         .append(\"rect\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * zoom) - margin;\n         })\n         .attr(\"width\", (w-margin) / dataset.length - barPadding)\n         .attr(\"height\", function(d) {\n            return d * zoom;\n         })\n         .attr(\"fill\", function(d) {\n//            return \"rgb(0, 0, \" + ( ( (d-20) * 10 ) + 100 ) + \")\";\n            return \"rgb(0, 51, 255)\";\n                     });\n\t\t \n   canvas.selectAll(\"text\")\n         .data(datasetT)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n          .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin + ((w-margin) / dataset.length - barPadding ) / 2;\n         })\n        .attr(\"y\", function(d) {\n            return h;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"black\");\n\n/*    canvas.selectAll(\"text\")\n         .data(dataset)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + (w / dataset.length - barPadding) / 2  + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * 4) + 14  - margin;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"white\");\n*/\n   // X 軸の生成\n//   canvas.append(\"g\")\n//         .attr(\"class\", \"axisBottom\")\n//         .attr(\"transform\", \"translate(0,\" + (h - margin) + \")\")\n//         .call(xAxis);\n\n   // Y 軸の生成\n   canvas.append(\"g\")\n         .attr(\"class\", \"axisLeft\")\n         .attr(\"transform\", \"translate(\" + margin + \",0)\")\n         .call(yAxis);\n\t\t \n\t\t \n   var m =  0;\n   var mh = 0;\n   var mm = 0;\n   var mt = 0;\n   for(var i in op_a2){\n\t   if (m < Number(op_a2[i].AMBIENTTEMP)) {\n\t       m = Number(op_a2[i].AMBIENTTEMP);\n\t\t   mh = op_a2[i].HOUR;\n\t\t   mm = ( \"0\" + op_a2[i].MINUTE ).substr( -2 ) ;\n\t\t   mt = op_a2[i].AMBIENTTEMP;\n    //console.log(\"max found was \" + mh + \":\" + mm + \" \" + mt);\n\t   }\n   }\n\n   m = mh + \":\" + mm;\n\n   window.onload = function onLoad() {\n      var target1 = document.getElementById(\"output1\");\n         target1.innerHTML = m;\n      var target2 = document.getElementById(\"output2\");\n         target2.innerHTML = mt;\n\t}\n\t\n</script>\n</head>\n<body>\n\n<div id=\"a-box\" style=\"background-color: #87cefa; padding: 20px;\">\n\t<h1>データベースからのIoTデータ表示</h1>\n\t<br />\n\t<p>\n\t\tデータベースに保存されたIoTデータを可視化します<br />\n\t</p>\n</div>\n\n<div id=\"b-box\" style=\"background-color: #ecf2fe; padding: 20px; \">\n\t\t<h2>最高値の時刻</h2>\n\t\t\t<div style=\"text-align:left\" id=\"output0\"></div>\n\t\t\t<div style=\"text-align:left;font-size: 18pt\" id=\"output1\"></div>\n\t\t<h2>最高値 </h2>\n\t\t\t<span style=\"text-align:left;font-size: 18pt\" id=\"output2\"></span> ℃\n</div>\n</body>\n</html>","x":690,"y":420,"wires":[["5d901718.3c51f8"]]},{"id":"5d901718.3c51f8","type":"http response","z":"64589e61.60898","name":"","x":850,"y":420,"wires":[]},{"id":"422b2203.7d68e4","type":"function","z":"64589e61.60898","name":"stringify","func":"var m = JSON.stringify(msg.payload);\nmsg.payload.op = m;\nreturn msg;","outputs":1,"noerr":0,"x":520,"y":380,"wires":[["d1c0278d.5bf49","fdd5ab25.ad1cd8"]]},{"id":"def4328.f99acd","type":"function","z":"64589e61.60898","name":"センサー値を待避","func":"msg.sensor = {\n        \"accelX\": msg.payload.d.accelX,\n        \"accelY\": msg.payload.d.accelY,\n        \"accelZ\": msg.payload.d.accelZ,\n        \"ambientTemp\": msg.payload.d.ambientTemp,\n        \"gyroX\": msg.payload.d.gyroX,\n        \"gyroY\": msg.payload.d.gyroY,\n        \"gyroZ\": msg.payload.d.gyroZ,\n        \"humidity\": msg.payload.d.humidity,\n        \"light\": msg.payload.d.light,\n        \"magX\": msg.payload.d.magX,\n        \"magY\": msg.payload.d.magY,\n        \"magZ\": msg.payload.d.magZ,\n        \"objectTemp\": msg.payload.d.objectTemp,\n};\n\nreturn msg;\n","outputs":1,"noerr":0,"x":530,"y":140,"wires":[["8bcc302e.8dbd58"]]},{"id":"ba9d26f1.6a516","type":"debug","z":"64589e61.60898","name":"書き込みデータ","active":true,"console":"false","complete":"payload","x":740,"y":260,"wires":[]},{"id":"838fa4c.eef7fd8","type":"comment","z":"64589e61.60898","name":"DBからのデータを可視化","info":"","x":150,"y":340,"wires":[]},{"id":"ecfd037.e72c4","type":"dashDB out","z":"64589e61.60898","service":"","table":"SENSOR2DB","name":"dashDBへ書き込み","x":750,"y":220,"wires":[]},{"id":"1f8c6452.0e2c14","type":"dashDB in","z":"64589e61.60898","service":"","query":"select hour,minute,ambienttemp, objecttemp  from SENSOR2DB where (minute%10)=0;","params":"","name":"dashDBから読み込み","x":320,"y":380,"wires":[["422b2203.7d68e4"]]}]

#サンプル3:センサータグ(CC2650)からのIoTデータを指定した間隔でdashDBへ書き込み、それを読み出してhtmlで表示
下記のフローではセンサータグCC2650からのIoTデータを指定した間隔でdashDBへ書き込み、それを表示します。

  1. センサータグCC2650からデータを取得します
  2. 指定した間隔でdashDBへ直接書き込みます
  3. 必要に応じ、「センサー値を出力」functionノードを開き、冒頭のインターバル値を調整します
  4. 必要に応じ、緑色のデータベースから読み出すノードのSQL文を変更して、読み出すデータを選択します

スクリーンショット 2016-09-08 19.10.41.png

DBへ書き込み、選択して表示
[{"id":"9b802212.ab298","type":"inject","z":"f2a0ab65.012a4","name":"1秒毎","topic":"","payload":"","payloadType":"date","repeat":"1","crontab":"","once":false,"x":90,"y":220,"wires":[[]]},{"id":"7fc9fcab.7ae5ac","type":"inject","z":"f2a0ab65.012a4","name":"restart","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"x":90,"y":260,"wires":[[]]},{"id":"db213626.dc386","type":"comment","z":"f2a0ab65.012a4","name":"IoTデータを指定した間隔でDBへ書き込み","info":"","x":180,"y":80,"wires":[]},{"id":"6e9b276c.ffdf2","type":"function","z":"f2a0ab65.012a4","name":"日付時刻の追加","func":"var d = new Date();\nvar localTime = d.getTime();\nvar localOffset = d.getTimezoneOffset() * 60000;\nvar utc = localTime + localOffset;\nvar offset = -9.0;\nvar result = utc - (3600000 * offset);\nvar date = parseInt(new Date(result) / 1000);\nvar dt = new Date(result);\n\nvar year = dt.getFullYear();\nvar month = dt.getMonth()+1;\nvar day = dt.getDate();\nvar hour = dt.getHours();\nvar minute = dt.getMinutes();\nvar second = dt.getSeconds();\n//if (!msg.payload) {\n//    msg.payload = { \"initial\": \"value\" };\n//}\nif (!msg.date) {\n    msg.date = { \"initial\": \"value\" };\n}\nmsg.date = {\n        \"date\": date,\n        \"year\": year,\n        \"month\": month,\n        \"day\": day,\n        \"hour\": hour,\n        \"minute\": minute,\n        \"second\": second\n};\nreturn msg;","outputs":1,"noerr":0,"x":281,"y":160,"wires":[["90078fcf.843928"]]},{"id":"1800effa.3c6348","type":"function","z":"f2a0ab65.012a4","name":"表へ書き込む","func":"msg.payload = \n{ \n\tDATE : msg.date.date,\n\tDAY : msg.date.day,\n\tHOUR : msg.date.hour,\n\tMINUTE : msg.date.minute,\n\tMONTH : msg.date.month,\n\tSECOND : msg.date.second,\n\tYEAR : msg.date.year,\n\tACCELX : msg.sensor.accelX,\n\tACCELY : msg.sensor.accelY,\n\tACCELZ : msg.sensor.accelZ,\n\tAMBIENTTEMP : msg.sensor.ambientTemp,\n\tGYROX : msg.sensor.gyroX,\n\tGYROY : msg.sensor.gyroY,\n\tGYROZ : msg.sensor.gyroZ,\n\tHUMIDITY : msg.sensor.humidity,\n\tLIGHT : msg.sensor.light,\n    MAGX : msg.sensor.magX,\n\tMAGY :msg.sensor.magY,\n\tMAGZ : msg.sensor.magZ,\n\tOBJECTTEMP : msg.sensor.objectTemp\n};\n\nreturn msg;\n","outputs":1,"noerr":0,"x":500,"y":240,"wires":[["3eb9243.1b9d1dc"]]},{"id":"124f8c12.f03f4c","type":"function","z":"f2a0ab65.012a4","name":"センサー値を出力","func":"var sampling_min_interval = 1;\nvar sampling_sec_interval = 60;     // データを出力する間隔\n\n/*\nvar sum = 0, average = 0;\nvar sen1 = Math.floor(Math.random () * 10) + 1; // センサー値を生成(シミュレート)\n\nif ( !context.array ) {\n    context.array = new Array (10); //直近10件分を保持\n}\nvar shifted = context.array.shift();\ncontext.array.push(sen1);           // 最新の値を保存\nvar length = context.array.length;\n\nfor (k=0; k<length; k++) {\n        sum = sum + context.array[k];   // 合計を算出\n}\n\nvar hour = JSON.stringify(msg.date.hour);\nvar min_org  = JSON.stringify(msg.date.minute);\nvar min = ( \"0\" + min_org ).substr( -2 );       // 一桁分の場合、二桁に\nvar sec_org  = JSON.stringify(msg.date.second);\nvar sec = ( \"0\" + sec_org ).substr( -2 );       // 一桁秒の場合、二桁に\nvar time = hour + \":\" + min + \":\" + sec;\n\naverage = sum / length;\nvar data = [[time],[sen1],[average]];\nmsg.sensor.average = average;\n*/\nif ( ( msg.date.second % sampling_sec_interval ) !== 0 ) return;\nif ( ( msg.date.minute % sampling_min_interval ) !== 0 ) return;\nreturn msg;\n","outputs":1,"noerr":0,"x":290,"y":240,"wires":[["1800effa.3c6348"]]},{"id":"f6b0debb.082e48","type":"ibmiot in","z":"f2a0ab65.012a4","authentication":"quickstart","apiKey":"","inputType":"evt","deviceId":"","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT","service":"quickstart","allDevices":"","allApplications":"","allDeviceTypes":true,"allEvents":true,"allCommands":"","allFormats":"","qos":0,"x":70,"y":160,"wires":[["6e9b276c.ffdf2"]]},{"id":"e99b18e9.c62eb8","type":"http in","z":"f2a0ab65.012a4","name":"","url":"/test34","method":"get","swaggerDoc":"","x":90,"y":400,"wires":[["92cc3f19.ad62b8"]]},{"id":"cdf0fddf.c45b08","type":"debug","z":"f2a0ab65.012a4","name":"op","active":true,"console":"false","complete":"payload.op","x":750,"y":440,"wires":[]},{"id":"7002bbf9.47486c","type":"template","z":"f2a0ab65.012a4","name":"htmlを返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n   <meta charset=\"utf-8\">\n   <title>データベースからのIoTデータ表示</title>\n      <script src=\"https://d3js.org/d3.v4.min.js\"></script>\n\n   <style type=\"text/css\">\n         /* ここにスタイルルールを追加します */\n      .axis path,\n      .axis line {\n         fill: none;\n         stroke: black;\n         shape-rendering: crispEdges;\n      }\n      .axis text {\n         font-family: sans-serif;\n         font-size: 11px;\n      }\n   </style>\n\n   <div id=\"op\" foo={{payload.op}}/>\n\n<script type=\"text/javascript\">\n\nvar op_a = document.getElementById( 'op' ).getAttribute( 'foo' );\t//データを取得\nop_a = op_a.substr( 0, op_a.length-1 ) ;\t//末尾の\"/\"でエラーになるので\nvar op_a2 = JSON.parse(op_a);\t//JSON文字列からjavascriptオブジェクトを復元\n\nvar op_a3 = new Array();\nfor(var i in op_a2){\n\top_a3.push(op_a2[i].AMBIENTTEMP);\t//AMBIENTTEMPを取り出して配列op_a3に順次格納\n}\n\nvar op_a5 = new Array();\nfor(var i in op_a2){\n\top_a5.push(op_a2[i].HOUR + \":\" + (( \"0\" + op_a2[i].MINUTE ).substr( -2 )));\n}\n\n   // 幅( Width )と高さ( height )\n   var w = 800;\n   var h = 300;\n   var zoom =5;\n   var barPadding = 1;  // 棒グラフの棒と棒の間隔\n   var margin = 30;     // グラフ表示域のまわりの余白\n   \n   var dataset = op_a3;\n   var datasetT = op_a5;\n   \n   // スケール関数の生成\n   var xScale = d3.scaleLinear()\n         .domain([0, d3.max(dataset, function(d) { return d; })])\n         .range([margin, w + margin * 2]);\n\n   var yScale = d3.scaleLinear()\n            .domain([0, (h-margin) / zoom]) // Y軸のスケールを棒グラフと一致させる\n            .range([h-margin, 0]);    // Y軸表示場所\n\n   // X 軸の定義\n   var xAxis = d3.axisBottom()\n        .scale(xScale);\n\n   // Y 軸の定義\n   var yAxis = d3.axisLeft(yScale);\n   \n   // SVG 要素の生成\n   var canvas = d3.select(\"body\")\n         .append(\"svg\")\n         .attr(\"width\", w)\n         .attr(\"height\", h);\n\n   canvas.selectAll(\"rect\")\n         .data(dataset)\n         .enter()\n         .append(\"rect\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * zoom) - margin;\n         })\n         .attr(\"width\", (w-margin) / dataset.length - barPadding)\n         .attr(\"height\", function(d) {\n            return d * zoom;\n         })\n         .attr(\"fill\", function(d) {\n//            return \"rgb(0, 0, \" + ( ( (d-20) * 10 ) + 100 ) + \")\";\n            return \"rgb(0, 51, 255)\";\n                     });\n\t\t \n   canvas.selectAll(\"text\")\n         .data(datasetT)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n          .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin + ((w-margin) / dataset.length - barPadding ) / 2;\n         })\n        .attr(\"y\", function(d) {\n            return h;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"black\");\n\n/*    canvas.selectAll(\"text\")\n         .data(dataset)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + (w / dataset.length - barPadding) / 2  + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * 4) + 14  - margin;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"white\");\n*/\n   // X 軸の生成\n//   canvas.append(\"g\")\n//         .attr(\"class\", \"axisBottom\")\n//         .attr(\"transform\", \"translate(0,\" + (h - margin) + \")\")\n//         .call(xAxis);\n\n   // Y 軸の生成\n   canvas.append(\"g\")\n         .attr(\"class\", \"axisLeft\")\n         .attr(\"transform\", \"translate(\" + margin + \",0)\")\n         .call(yAxis);\n\t\t \n\t\t \n   var m =  0;\n   var mh = 0;\n   var mm = 0;\n   var mt = 0;\n   for(var i in op_a2){\n\t   if (m < Number(op_a2[i].AMBIENTTEMP)) {\n\t       m = Number(op_a2[i].AMBIENTTEMP);\n\t\t   mh = op_a2[i].HOUR;\n\t\t   mm = ( \"0\" + op_a2[i].MINUTE ).substr( -2 ) ;\n\t\t   mt = op_a2[i].AMBIENTTEMP;\n    //console.log(\"max found was \" + mh + \":\" + mm + \" \" + mt);\n\t   }\n   }\n\n   m = mh + \":\" + mm;\n\n   window.onload = function onLoad() {\n      var target1 = document.getElementById(\"output1\");\n         target1.innerHTML = m;\n      var target2 = document.getElementById(\"output2\");\n         target2.innerHTML = mt;\n\t}\n\t\n</script>\n</head>\n<body>\n\n<div id=\"a-box\" style=\"background-color: #87cefa; padding: 20px;\">\n\t<h1>データベースからのIoTデータ表示</h1>\n\t<br />\n\t<p>\n\t\tデータベースに保存されたIoTデータを可視化します<br />\n\t</p>\n</div>\n\n<div id=\"b-box\" style=\"background-color: #ecf2fe; padding: 20px; \">\n\t\t<h2>最高値の時刻</h2>\n\t\t\t<div style=\"text-align:left\" id=\"output0\"></div>\n\t\t\t<div style=\"text-align:left;font-size: 18pt\" id=\"output1\"></div>\n\t\t<h2>最高値 </h2>\n\t\t\t<span style=\"text-align:left;font-size: 18pt\" id=\"output2\"></span> ℃\n</div>\n</body>\n</html>","x":770,"y":400,"wires":[["928a0ea8.cbdab"]]},{"id":"928a0ea8.cbdab","type":"http response","z":"f2a0ab65.012a4","name":"","x":910,"y":400,"wires":[]},{"id":"43a2beab.5938e8","type":"function","z":"f2a0ab65.012a4","name":"stringify","func":"var m = JSON.stringify(msg.payload);\nmsg.payload.op = m;\nreturn msg;","outputs":1,"noerr":0,"x":600,"y":400,"wires":[["7002bbf9.47486c","cdf0fddf.c45b08"]]},{"id":"6953c1c.cf749c","type":"dashDB in","z":"f2a0ab65.012a4","service":"dashDB-rk","query":"select hour,minute,ambienttemp, objecttemp  from SENSOR2DB where (minute%10)=0;","params":"","name":"dashDBから読み込み","x":300,"y":400,"wires":[[]]},{"id":"90078fcf.843928","type":"function","z":"f2a0ab65.012a4","name":"センサー値を待避","func":"msg.sensor = {\n        \"accelX\": msg.payload.d.accelX,\n        \"accelY\": msg.payload.d.accelY,\n        \"accelZ\": msg.payload.d.accelZ,\n        \"ambientTemp\": msg.payload.d.ambientTemp,\n        \"gyroX\": msg.payload.d.gyroX,\n        \"gyroY\": msg.payload.d.gyroY,\n        \"gyroZ\": msg.payload.d.gyroZ,\n        \"humidity\": msg.payload.d.humidity,\n        \"light\": msg.payload.d.light,\n        \"magX\": msg.payload.d.magX,\n        \"magY\": msg.payload.d.magY,\n        \"magZ\": msg.payload.d.magZ,\n        \"objectTemp\": msg.payload.d.objectTemp,\n};\n\nreturn msg;\n","outputs":1,"noerr":0,"x":510,"y":160,"wires":[["124f8c12.f03f4c"]]},{"id":"7d0b0217.a388b4","type":"dashDB out","z":"f2a0ab65.012a4","service":"dashDB-rk","table":"SENSOR2DB","name":"dashDBへ書き込み","x":730,"y":240,"wires":[]},{"id":"3eb9243.1b9d1dc","type":"debug","z":"f2a0ab65.012a4","name":"書き込みデータ","active":true,"console":"false","complete":"payload","x":720,"y":280,"wires":[]},{"id":"92cc3f19.ad62b8","type":"dashDB in","z":"f2a0ab65.012a4","service":"dashDB-rk","query":"select hour,minute,ambienttemp, objecttemp  from SENSOR2DB where (minute%30)=0 and day=29;","params":"","name":"30分毎のデータを読み込み","x":320,"y":440,"wires":[["43a2beab.5938e8"]]},{"id":"b0c6261f.e2346","type":"dashDB in","z":"f2a0ab65.012a4","service":"dashDB-rk","query":"select hour,minute,ambienttemp, objecttemp  from SENSOR2DB where (minute%60)=0;","params":"","name":"一時間毎のデータを読み込み","x":320,"y":480,"wires":[[]]},{"id":"f15821f9.e9ba7","type":"dashDB in","z":"f2a0ab65.012a4","service":"dashDB-rk","query":"select month,day,hour,minute,ambienttemp, objecttemp  from SENSOR2DB where (minute%15)=0 and day=29 and hour<20;","params":"","name":"30分毎の日付も含めデータを読み込み","x":350,"y":560,"wires":[["4fa21c30.4eadd4"]]},{"id":"4fa21c30.4eadd4","type":"function","z":"f2a0ab65.012a4","name":"stringify","func":"var m = JSON.stringify(msg.payload);\nmsg.payload.op = m;\nreturn msg;","outputs":1,"noerr":0,"x":600,"y":560,"wires":[["5e1ab7c3.c3f428"]]},{"id":"5e1ab7c3.c3f428","type":"template","z":"f2a0ab65.012a4","name":"htmlを返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n   <meta charset=\"utf-8\">\n   <title>データベースからのIoTデータ表示</title>\n      <script src=\"https://d3js.org/d3.v4.min.js\"></script>\n\n   <style type=\"text/css\">\n         /* ここにスタイルルールを追加します */\n      .axis path,\n      .axis line {\n         fill: none;\n         stroke: black;\n         shape-rendering: crispEdges;\n      }\n      .axis text {\n         font-family: sans-serif;\n         font-size: 11px;\n      }\n   </style>\n\n   <div id=\"op\" foo={{payload.op}}/>\n\n<script type=\"text/javascript\">\n\nvar op_a = document.getElementById( 'op' ).getAttribute( 'foo' );\t//データを取得\nop_a = op_a.substr( 0, op_a.length-1 ) ;\t//末尾の\"/\"でエラーになるので\nvar op_a2 = JSON.parse(op_a);\t//JSON文字列からjavascriptオブジェクトを復元\n\nvar op_a3 = new Array();\nfor(var i in op_a2){\n\top_a3.push(op_a2[i].AMBIENTTEMP);\t//AMBIENTTEMPを取り出して配列op_a3に順次格納\n}\n\nvar op_a5 = new Array();\nfor(var i in op_a2){\n\top_a5.push(op_a2[i].HOUR + \":\" + (( \"0\" + op_a2[i].MINUTE ).substr( -2 )));\n}\n\n   // 幅( Width )と高さ( height )\n   var w = 800;\n   var h = 300;\n   var zoom =5;\n   var barPadding = 1;  // 棒グラフの棒と棒の間隔\n   var margin = 30;     // グラフ表示域のまわりの余白\n   \n   var dataset = op_a3;\n   var datasetT = op_a5;\n   \n   // スケール関数の生成\n   var xScale = d3.scaleLinear()\n         .domain([0, d3.max(dataset, function(d) { return d; })])\n         .range([margin, w + margin * 2]);\n\n   var yScale = d3.scaleLinear()\n            .domain([0, (h-margin) / zoom]) // Y軸のスケールを棒グラフと一致させる\n            .range([h-margin, 0]);    // Y軸表示場所\n\n   // X 軸の定義\n   var xAxis = d3.axisBottom()\n        .scale(xScale);\n\n   // Y 軸の定義\n   var yAxis = d3.axisLeft(yScale);\n   \n   // SVG 要素の生成\n   var canvas = d3.select(\"body\")\n         .append(\"svg\")\n         .attr(\"width\", w)\n         .attr(\"height\", h);\n\n   canvas.selectAll(\"rect\")\n         .data(dataset)\n         .enter()\n         .append(\"rect\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * zoom) - margin;\n         })\n         .attr(\"width\", (w-margin) / dataset.length - barPadding)\n         .attr(\"height\", function(d) {\n            return d * zoom;\n         })\n         .attr(\"fill\", function(d) {\n//            return \"rgb(0, 0, \" + ( ( (d-20) * 10 ) + 100 ) + \")\";\n            return \"rgb(0, 51, 255)\";\n                     });\n\t\t \n   canvas.selectAll(\"text\")\n         .data(datasetT)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n          .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + margin + ((w-margin) / dataset.length - barPadding ) / 2;\n         })\n        .attr(\"y\", function(d) {\n            return h;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"black\");\n\n/*    canvas.selectAll(\"text\")\n         .data(dataset)\n         .enter()\n         .append(\"text\")\n         .text(function(d) {\n            return d;\n         })\n         .attr(\"text-anchor\", \"middle\")\n         .attr(\"x\", function(d, i) {\n            return i * ((w-margin) / dataset.length) + (w / dataset.length - barPadding) / 2  + margin;\n         })\n         .attr(\"y\", function(d) {\n            return h - (d * 4) + 14  - margin;\n         })\n         .attr(\"font-family\", \"sans-serif\")\n         .attr(\"font-size\", \"11px\")\n         .attr(\"fill\", \"white\");\n*/\n   // X 軸の生成\n//   canvas.append(\"g\")\n//         .attr(\"class\", \"axisBottom\")\n//         .attr(\"transform\", \"translate(0,\" + (h - margin) + \")\")\n//         .call(xAxis);\n\n   // Y 軸の生成\n   canvas.append(\"g\")\n         .attr(\"class\", \"axisLeft\")\n         .attr(\"transform\", \"translate(\" + margin + \",0)\")\n         .call(yAxis);\n\t\t \n\t\t \n   var m =  0;\n   var mh = 0;\n   var mm = 0;\n   var mt = 0;\n   var month = 0;\n   var day = 0;\n   for(var i in op_a2){\n\t   if (m < Number(op_a2[i].AMBIENTTEMP)) {\n\t       m = Number(op_a2[i].AMBIENTTEMP);\n\t\t   month = op_a2[i].MONTH;\n\t\t   day = op_a2[i].DAY; \n\t\t   mh = op_a2[i].HOUR;\n\t\t   mm = ( \"0\" + op_a2[i].MINUTE ).substr( -2 ) ;\n\t\t   mt = op_a2[i].AMBIENTTEMP;\n    //console.log(\"max found was \" + mh + \":\" + mm + \" \" + mt);\n\t   }\n   }\n\n   m = mh + \":\" + mm;\n\n   window.onload = function onLoad() {\n      var target1 = document.getElementById(\"output1\");\n         target1.innerHTML = m;\n      var target2 = document.getElementById(\"output2\");\n         target2.innerHTML = mt;\n\n\t  var target3 = document.getElementById(\"output3\");\n         target3.innerHTML = month;\n      var target4 = document.getElementById(\"output4\");\n         target4.innerHTML = day;\n\t}\n\t\n</script>\n</head>\n<body>\n\n<div id=\"a-box\" style=\"background-color: #87cefa; padding: 20px;\">\n\t<h1>データベースからのIoTデータ表示</h1>\n\t<br />\n\t<p>\n\t\tデータベースに保存されたIoTデータを可視化します<br />\n\t</p>\n</div>\n\n<div id=\"b-box\" style=\"background-color: #ecf2fe; padding: 20px; \">\n\t\t<h2>日付</h2>\n\t\t\t<span style=\"text-align:left;font-size: 18pt\" id=\"output3\"></span> 月\n\t\t\t<span style=\"text-align:left;font-size: 18pt\" id=\"output4\"></span> 日\n\t\t<h2>最高値の時刻</h2>\n\t\t\t<div style=\"text-align:left\" id=\"output0\"></div>\n\t\t\t<div style=\"text-align:left;font-size: 18pt\" id=\"output1\"></div>\n\t\t<h2>最高値 </h2>\n\t\t\t<span style=\"text-align:left;font-size: 18pt\" id=\"output2\"></span> ℃\n</div>\n</body>\n</html>","x":770,"y":560,"wires":[["3609e22b.58e26e"]]},{"id":"3609e22b.58e26e","type":"http response","z":"f2a0ab65.012a4","name":"","x":910,"y":560,"wires":[]},{"id":"77f5b038.8b8ce8","type":"http in","z":"f2a0ab65.012a4","name":"","url":"/test35","method":"get","swaggerDoc":"","x":90,"y":560,"wires":[["f15821f9.e9ba7"]]},{"id":"24c5f10a.912c06","type":"comment","z":"f2a0ab65.012a4","name":"DBから読み出したデータをhtmlで表示","info":"","x":170,"y":360,"wires":[]}]

#サンプル4:AlpS Smart IoT ModuleからのIoTデータを指定した間隔でdashDBへ書き込み、それを読み出してhtmlで表示
下記のフローではAlps Smart IoT ModuleからのIoTデータを指定した間隔でdashDBへ書き込み、それを表示します。

  1. Alps Smart IoT Moduleからデータを取得します
  2. 指定した間隔でdashDBへ直接書き込みます。このサンプルではALPSIOTという表へ書き込んでいます
  3. 2つのオレンジ色のTemplateノードを開き「このIoTアプリの名前」部分をそれぞれのNode-REDアプリ名に一致させます
  4. 必要に応じ、「センサー値を出力」functionノードを開き、冒頭のインターバル値を調整します
  5. 必要に応じ、緑色のデータベースから読み出すノードのSQL文を変更して、読み出すデータを選択します

スクリーンショット 2017-01-30 10.35.05.png
スクリーンショット 2017-01-30 10.32.59.png

DBへ書き込み、選択して表示
[{"id":"f65c24c1.63c7b8","type":"http in","z":"2f7e4ebb.3a553a","name":"","url":"/test54a","method":"get","swaggerDoc":"","x":110,"y":100,"wires":[["53dec3e1.f5c2dc"]]},{"id":"6b45354f.4e0f2c","type":"http response","z":"2f7e4ebb.3a553a","name":"","x":490,"y":100,"wires":[]},{"id":"53dec3e1.f5c2dc","type":"template","z":"2f7e4ebb.3a553a","name":"入力用test54aを返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE HTML>\n<html>\n<head>\n  <title>IoT Quick Dashboard</title>\n  <meta charset=\"utf-8\" />\n  <style type=\"text/css\">\n  #basic {\n  }\n\n  .a1 {\n    background-color:  #98d98e;\n    height: 120px;\n    padding: 20px;\n  }\n  .b1 {\n    background-color:  #cee4ae;\n    height: 500px;\n    text-align:left;\n    font-size: 18pt;\n    padding: 20px;\n    font-family: Meiryo;\n  }\n  .y1 {\n    background-color: #e4dc8a;\n    height: 250px;\n  }\n  .z1 {\n    height: 25px;\n    background-color: #8f8667;\n    font-size: 18px;\n    text-align: center;\n  }\n\n  </style>\n</head>\n<body>\n  <div id='basic'>\n    <div class='a1'>\n      <h2>IoT Quick Dashboard</h2><br>\n      データベースに保存されたIoTデータを可視化します\n    </div>\n    <div class='b1'>\n      <b>入力!</b>\n      <P>表示対象の属性と期間を指定します。</P>\n      <form action=\"http://このIoTアプリの名前.mybluemix.net/test55a\" method=\"get\">\n        <select name=\"machine\" style=\"font-size:24px\">\n          <option>ALPSIOT</option>\n          <option>ALPSIOT2</option>\n        </select><br><br>\n        この日時から <input type=\"datetime-local\" name=\"starttime\" value=\"2014-01-21T10:00\" step=\"60\"  style=\"font-size:18px\"><br>\n        この日時まで  <input type=\"datetime-local\" name=\"endtime\" value=\"2014-01-21T16:00\" step=\"60\"  style=\"font-size:18px \"><br><br>\n        <button type=\"submit\" name=\"submit\" value=\"送信\">\n          <font size=\"2\">表示要求を</font><font size=\"5\" color=\"red\">送信!</font>\n        </button>\n        <INPUT type=\"reset\" value=\"リセット\"><BR><BR>\n        </FORM>\n      </div>\n      <div class=\"y1\">\n        参考URL\n        <ul>\n          <li><a href=\"http://qiita.com/egplnt/items/af867711a7191923b2ff\">Watson IoT Platformを使ってみる</a></li>\n          <li><a href=\"https://internetofthings.ibmcloud.com/#/\">Watson IoT Platform</a></li>\n          <li><a href=\"https://developer.ibm.com/recipes/tutorials/use-the-simulated-device-to-experience-the-iot-foundation/\">Recipe - Simulator</a></li>\n        </ul>\n        マニュアル\n        <ul>\n          <li><a href=\"http://ibm.com/iot\">IBM IoT</a></li>\n          <li><a href=\"https://docs.internetofthings.ibmcloud.com/ja/\">Watson IoT Platform資料ページ</a></li>\n          <li><a href=\"https://developer.ibm.com/recipes/\">Recipe</a></li>\n        </ul>\n      </div>\n      <div class=\"z1\">\n        copyright (c) abc.com All right reserved.\n      </div>\n    </div>\n  </body>\n  </html>\n","x":300,"y":100,"wires":[["6b45354f.4e0f2c"]]},{"id":"3f28fb34.21ad8c","type":"http in","z":"2f7e4ebb.3a553a","name":"","url":"/test55a","method":"get","swaggerDoc":"","x":110,"y":200,"wires":[["c95233b9.8ea46"]]},{"id":"fa420c3e.f2347","type":"comment","z":"2f7e4ebb.3a553a","name":"DBから値を取得し表示","info":"","x":120,"y":160,"wires":[]},{"id":"239ed8cc.23c82","type":"comment","z":"2f7e4ebb.3a553a","name":"表示する属性と期間を指定","info":"","x":130,"y":60,"wires":[]},{"id":"c95233b9.8ea46","type":"function","z":"2f7e4ebb.3a553a","name":"時間を取得","func":"msg.tgt = msg.payload.tgt;\n\nvar arr1 = msg.payload.starttime.split(/[T]/);\nmsg.starttime = arr1[0] + \" \" + arr1[1] + \":00\";\n\nvar arr2 = msg.payload.endtime.split(/[T]/);\nmsg.endtime = arr2[0] + \" \" + arr2[1] + \":00\";\n\n//msg.newstarttime = parseInt ( Date(msg.startime) );\n//msg.newendtime = parseInt ( Date(msg.endime)  );\n\n\nvar st = msg.startime;\n\nmsg.newstarttime = Date.parse(st);\n\n//var st_parse = st.replace(/-/g, '/');\n//msg.newstarttime = Date.parse(st_parse);\n\n//msg.newstarttime = Date.parse( st.datetime.replace( /-/g, '/') ) / 1000;\n//msg.newstarttime = Date.parse( st ) / 1000;\n\n//var et = msg.endime;\nvar st_parse = msg.starttime.replace(/-/g, '/');\nmsg.newstarttime = Date.parse(st_parse) / 1000;\n\nvar et_parse = msg.endtime.replace(/-/g, '/');\nmsg.newendtime = Date.parse(et_parse) / 1000;\n\n//msg.newendtime = Date.parse( et.replace( /-/g, '/') ) / 1000;\n//msg.newendtime = Date.parse( et ) / 1000;\n\n//var ts = \"2011-10-14 00:00:00\";\n//print( Date.parse( ts.replace( /-/g, '/') ) / 1000 );\n\n\nmsg.machine = msg.payload.machine;\n\nreturn msg;","outputs":1,"noerr":0,"x":270,"y":200,"wires":[["91c4ec0d.755b68"]]},{"id":"4c2f7051.8ad29","type":"function","z":"2f7e4ebb.3a553a","name":"結果をセット","func":"\nvar i = 0;\nvar len = msg.payload.length;\nvar arr01 = new Array(); var arr02 = new Array(); var arr03 = new Array(); var arr04 = new Array();\nvar arr05 = new Array(); var arr06 = new Array(); var arr07 = new Array(); var arr08 = new Array();\nvar arr09 = new Array(); var arr10 = new Array(); var arr11 = new Array(); var arr12 = new Array();\nvar arr13 = new Array();\n\nfor (i; i < len; i++) {\n    //var c1 = msg.payload[i]['DATE'];\n    var c1 = i;\n    arr01.push([c1,parseFloat(msg.payload[i]['DATE'])]);\n    arr02.push([c1,parseFloat(msg.payload[i]['HOUR'])]);\n    arr03.push([c1,parseFloat(msg.payload[i]['MINUTE'])]);\n    arr04.push([c1,parseFloat(msg.payload[i]['ACCELX'])]);\n    arr05.push([c1,parseFloat(msg.payload[i]['ACCELY'])]);\n    arr06.push([c1,parseFloat(msg.payload[i]['ACCELZ'])]);\n    arr07.push([c1,parseFloat(msg.payload[i]['AMBIENTLIGHT'])]);\n    arr08.push([c1,parseFloat(msg.payload[i]['GEOMAGNETICX'])]);\n    arr09.push([c1,parseFloat(msg.payload[i]['GEOMAGNETICY'])]);\n    arr10.push([c1,parseFloat(msg.payload[i]['GEOMAGNETICZ'])]);\n    arr11.push([c1,parseFloat(msg.payload[i]['HUMIDITY'])]);\n    arr12.push([c1,parseFloat(msg.payload[i]['PRESSURE'])]);\n    arr13.push([c1,parseFloat(msg.payload[i]['UV'])]);\n}\n\nmsg.payload.r01 = JSON.stringify(arr01);\nmsg.payload.r02 = JSON.stringify(arr02);\nmsg.payload.r03 = JSON.stringify(arr03);\nmsg.payload.r04 = JSON.stringify(arr04);\nmsg.payload.r05 = JSON.stringify(arr05);\nmsg.payload.r06 = JSON.stringify(arr06);\nmsg.payload.r07 = JSON.stringify(arr07);\nmsg.payload.r08 = JSON.stringify(arr08);\nmsg.payload.r09 = JSON.stringify(arr09);\nmsg.payload.r10 = JSON.stringify(arr10);\nmsg.payload.r11 = JSON.stringify(arr11);\nmsg.payload.r12 = JSON.stringify(arr12);\nmsg.payload.r13 = JSON.stringify(arr13);\n\n/*\nmsg.payload = JSON.stringify(arr01) + \"&\" + JSON.stringify(arr02) + \"&\" + JSON.stringify(arr03) + \"&\" + JSON.stringify(arr04) +\n              JSON.stringify(arr05) + \"&\" + JSON.stringify(arr06) + \"&\" + JSON.stringify(arr07) + \"&\" + JSON.stringify(arr08) +\n              JSON.stringify(arr09) + \"&\" + JSON.stringify(arr10) + \"&\" + JSON.stringify(arr11) + \"&\" + JSON.stringify(arr12) +\n              JSON.stringify(arr13);\n*/\n\nreturn msg;\n","outputs":1,"noerr":0,"x":580,"y":200,"wires":[["a1b765cf.fdbfa"]]},{"id":"a1b765cf.fdbfa","type":"template","z":"2f7e4ebb.3a553a","name":"test55a.html返却","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE HTML>\n<html>\n <head>\n  <title>IoT Quick Dashboard</title>\n  <meta charset=\"utf-8\" />\n<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n<script type=\"test/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n\n\n<style type=\"text/css\">\n#basic {\n}\n\n.a1 {\n  background-color:  #98d98e;\n  height: 120px;\n  padding: 20px;\n}\n.c1 {\n  background-color:  #cee4ae;\n  height: 500px;\n  text-align:left;\n  font-size: 18pt;\n  padding: 20px;\n  font-family: Meiryo;\n}\n\n#d1 {\n  clear: both;\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #c1d8ac;\n}\n#d2 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #b9d08b;\n}\n#d3 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #badcad;\n}\n\n#e1 {\n  clear: both;\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #c1d8ac;\n}\n#e2 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #b9d08b;\n}\n#e3 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #badcad;\n}\n\n#f1 {\n  clear: both;\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #c1d8ac;\n}\n#f2 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #b9d08b;\n}\n#f3 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #badcad;\n}\n\n#g1 {\n  clear: both;\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #c1d8ac;\n}\n#g2 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #b9d08b;\n}\n#g3 {\n  float: left;\n  width: 400px;\n  height: 400px;\n  background-color:  #badcad;\n}\n\n.h1 {\n  clear: both;\n  height: 100px;\n  padding-left: 20px;\n  background-color:  #c1d8ac;\n}\n.j1 {\n  height: 100px;\n  padding-left: 20px;\n  background-color:  #98d98e;\n}\n\n.y1 {\n  background-color: #e4dc8a;\n  padding-left: 10px;\n  height: 250px;\n}\n.z1 {\n  height: 25px;\n  background-color: #8f8667;\n  font-size: 18px;\n  text-align: center;\n}\n\n</style>\n </head>\n <body>\n\n  <div id='basic'>\n\n    <div class='a1'>\n      <h2>IoT Quick Dashboard</h2><br>\n        データベースに保存されたIoTデータを可視化します\n    </div>\n\n    <div class='c1'>\n    <b>入力!</b>\n      <P>表示対象の属性と期間を指定します。</P>\n      <form action=\"http://このIoTアプリの名前.mybluemix.net/test55a\" method=\"get\">\n        <select name=\"machine\" style=\"font-size:24px\">\n            <option>ALPSIOT</option>\n            <option>ALPSIOT2</option>\n        </select><br><br>\n\n          この日時から <input type=\"datetime-local\" name=\"starttime\" value=\"2017-01-16T10:00\" step=\"60\"  style=\"font-size:18px\"><br>\n          この日時まで  <input type=\"datetime-local\" name=\"endtime\" value=\"2017-01-16T16:00\" step=\"60\"  style=\"font-size:18px \"><br><br>\n      <button type=\"submit\" name=\"submit\" value=\"送信\">\n      <font size=\"2\">表示要求を</font><font size=\"5\" color=\"red\">送信!</font>\n      </button>\n      <INPUT type=\"reset\" value=\"リセット\"><BR><BR>\n      </FORM>\n\n    </div>\n\n    <div id='d1' align=\"center\">\n      d1\n    </div>\n    <div id='d2' align=\"center\">\n      d2\n    </div>\n    <div id='d3' align=\"center\">\n      d3\n    </div>\n\n    <div id='e1' align=\"center\">\n      e1\n    </div>\n    <div id='e2' align=\"center\">\n      e2\n    </div>\n    <div id='e3' align=\"center\">\n      e3\n    </div>\n\n    <div id='f1' align=\"center\">\n      f1\n    </div>\n    <div id='f2' align=\"center\">\n      f2\n    </div>\n    <div id='f3' align=\"center\">\n      f3\n    </div>\n\n    <div id='g1' align=\"center\">\n      g1\n    </div>\n    <div id='g2' align=\"center\">\n      g2\n    </div>\n    <div id='g3' align=\"center\">\n      g3\n    </div>\n\n    <div class='h1' align=\"left\">\n      <h3>アラート</h3>\n    </div>\n    <div class='j1' align=\"center\">\n\n    </div>\n\n<div class=\"y1\">\n  参考URL\n  <ul>\n    <li><a href=\"http://qiita.com/egplnt/items/af867711a7191923b2ff\">Watson IoT Platformを使ってみる</a></li>\n    <li><a href=\"https://internetofthings.ibmcloud.com/#/\">Watson IoT Platform</a></li>\n    <li><a href=\"https://developer.ibm.com/recipes/tutorials/use-the-simulated-device-to-experience-the-iot-foundation/\">Recipe - Simulator</a></li>\n  </ul>\n  マニュアル\n  <ul>\n    <li><a href=\"http://ibm.com/iot\">IBM IoT</a></li>\n    <li><a href=\"https://docs.internetofthings.ibmcloud.com/ja/\">Watson IoT Platform資料ページ</a></li>\n    <li><a href=\"https://developer.ibm.com/recipes/\">Recipe</a></li>\n  </ul>\n</div>\n\n<div class=\"z1\">\n\tcopyright (c) abc.com All right reserved.\n</div>\n</div>\n\n\n<script>\n\ngoogle.load(\"visualization\", \"1\", {packages:[\"corechart\"]});\ngoogle.setOnLoadCallback(drawChart02);\n\nfunction drawChart02() {\n  d1ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"照度\"],[439,7.0007]] );\n  d1ChartData.removeRow(0);\n  d1ChartData.addRows( {{{ payload.r07 }}} );\n  d1ChartOptions = { title: '照度',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  d1Chart = new google.visualization.LineChart(document.getElementById('d1'));\n  d1Chart.draw(d1ChartData, d1ChartOptions);\n\n  d2ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"気圧\"],[439,7.0007]] );\n  d2ChartData.removeRow(0);\n  d2ChartData.addRows( {{{ payload.r12 }}} );\n  d2ChartOptions = { title: '気圧',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  d2Chart = new google.visualization.LineChart(document.getElementById('d2'));\n  d2Chart.draw(d2ChartData, d2ChartOptions);\n\n  d3ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"UV値\"],[439,7.0007]] );\n  d3ChartData.removeRow(0);\n  d3ChartData.addRows( {{{ payload.r13 }}} );\n  d3ChartOptions = { title: 'UV値',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  d3Chart = new google.visualization.LineChart(document.getElementById('d3'));\n  d3Chart.draw(d3ChartData, d3ChartOptions);\n\n  e1ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"加速度(X軸)\"],[439,7.0007]] );\n  e1ChartData.removeRow(0);\n  e1ChartData.addRows( {{{ payload.r04 }}} );\n  e1ChartOptions = { title: '加速度(X軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  e1Chart = new google.visualization.LineChart(document.getElementById('e1'));\n  e1Chart.draw(e1ChartData, e1ChartOptions);\n\n  e2ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"加速度(Y軸)\"],[439,7.0007]] );\n  e2ChartData.removeRow(0);\n  e2ChartData.addRows( {{{ payload.r05 }}} );\n  e2ChartOptions = { title: '加速度(Y軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  e2Chart = new google.visualization.LineChart(document.getElementById('e2'));\n  e2Chart.draw(e2ChartData, e2ChartOptions);\n\n  e3ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"加速度(Z軸)\"],[439,7.0007]] );\n  e3ChartData.removeRow(0);\n  e3ChartData.addRows( {{{ payload.r06 }}} );\n  e3ChartOptions = { title: '加速度(Z軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  e3Chart = new google.visualization.LineChart(document.getElementById('e3'));\n  e3Chart.draw(e3ChartData, e3ChartOptions);\n\n  f1ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"地磁気(X軸)\"],[439,7.0007]] );\n  f1ChartData.removeRow(0);\n  f1ChartData.addRows( {{{ payload.r08 }}} );\n  f1ChartOptions = { title: '地磁気(X軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  f1Chart = new google.visualization.LineChart(document.getElementById('f1'));\n  f1Chart.draw(f1ChartData, f1ChartOptions);\n\n  f2ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"地磁気(Y軸)\"],[439,7.0007]] );\n  f2ChartData.removeRow(0);\n  f2ChartData.addRows( {{{ payload.r09 }}} );\n  f2ChartOptions = { title: '地磁気(Y軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  f2Chart = new google.visualization.LineChart(document.getElementById('f2'));\n  f2Chart.draw(f2ChartData, f2ChartOptions);\n\n  f3ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"地磁気(Z軸)\"],[439,7.0007]] );\n  f3ChartData.removeRow(0);\n  f3ChartData.addRows( {{{ payload.r10 }}} );\n  f3ChartOptions = { title: '地磁気(Z軸)',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  f3Chart = new google.visualization.LineChart(document.getElementById('f3'));\n  f3Chart.draw(f3ChartData, f3ChartOptions);\n\n  g1ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"湿度\"],[439,7.0007]] );\n  g1ChartData.removeRow(0);\n  g1ChartData.addRows( {{{ payload.r11 }}} );\n  g1ChartOptions = { title: '湿度',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  g1Chart = new google.visualization.LineChart(document.getElementById('g1'));\n  g1Chart.draw(g1ChartData, g1ChartOptions);\n\n  g2ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"気圧\"],[439,7.0007]] );\n  g2ChartData.removeRow(0);\n  g2ChartData.addRows( {{{ payload.r12 }}} );\n  g2ChartOptions = { title: '気圧',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  g2Chart = new google.visualization.LineChart(document.getElementById('g2'));\n  g2Chart.draw(g2ChartData, g2ChartOptions);\n\n  g3ChartData = google.visualization.arrayToDataTable(\n    [[\"INCOMING_EVENT_CD\",\"UV値\"],[439,7.0007]] );\n  g3ChartData.removeRow(0);\n  g3ChartData.addRows( {{{ payload.r13 }}} );\n  g3ChartOptions = { title: 'UV値',\n    'titleTextStyle': { fontName: 'Meiryo UI', fontSize: 30},\n    legend: { position: 'bottom' } };\n  g3Chart = new google.visualization.LineChart(document.getElementById('g3'));\n  g3Chart.draw(g3ChartData, g3ChartOptions);\n\n};\n\n</script>\n\n</body>\n</html>\n","x":770,"y":200,"wires":[["2f29f9c6.825946"]]},{"id":"2f29f9c6.825946","type":"http response","z":"2f7e4ebb.3a553a","name":"","x":930,"y":200,"wires":[]},{"id":"88f972da.c66448","type":"debug","z":"2f7e4ebb.3a553a","name":"","active":true,"console":"false","complete":"false","x":580,"y":240,"wires":[]},{"id":"91c4ec0d.755b68","type":"dashDB in","z":"2f7e4ebb.3a553a","dashDB":"","service":"_ext_","query":"select * from ALPSIOT \nwhere date between ? and ?;","params":"msg.newstarttime,msg.newendtime","name":"","x":420,"y":200,"wires":[["4c2f7051.8ad29","88f972da.c66448"]]}]

#サンプル5:AlpS Smart IoT ModuleからのIoTデータをWebSocketでリアルタイム表示

下記のフローではAlps Smart IoT ModuleからのIoTデータをWebSocketでリアルタイムに表示します。

  1. Alps Smart IoT ModuleからのデータをWebSocketで出力します。このサンプルではwss/flow56aというsocketで出力していると想定しています
  2. オレンジ色のTemplateノードを開き「このIoTアプリの名前」部分をWebSocketを出力しているアプリ名に一致させます

スクリーンショット 2017-01-30 11.14.40.png
スクリーンショット 2017-01-30 11.14.50.png

センサーからのIoTデータをリアルタイムで表示
[{"id":"ed8f0bb.cd5e278","type":"template","z":"89d26c8f.7f48a","name":"test56a.htmlを返す","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<!DOCTYPE HTML>\n<html>\n <head>\n  <title>センサーからの情報を表示</title>\n  <meta charset=\"utf-8\" />\n<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n<script type=\"test/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n\n\n<style type=\"text/css\">\n#basic {\n  width: 1200px;\n  margin: auto;\n}\n\n.a1 {\n  background-color:  #98d98e;\n  padding: 20px;\n  height: 100px;\n}\n.b1 {\n  background-color:  #e4de8a;\n  padding-left: 20px;\n  height: 40px;\n  text-align:left;\n  font-size: 18pt\n}\n#d1 {\n  clear: both;\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #c1d8ac;\n}\n#d2 {\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #b9d08b;\n}\n#d3 {\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #badcad;\n}\n\n#e1 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #c1d8ac;\n}\n#e2 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #b9d08b;\n}\n#e3 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #badcad;\n}\n\n#f1 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #c1d8ac;\n}\n#f2 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #b9d08b;\n}\n#f3 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #badcad;\n}\n\n#g1 {\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #c1d8ac;\n}\n#g2 {\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #b9d08b;\n}\n#g3 {\n  float: left;\n  width: 400px;\n  height: 150px;\n  background-color:  #badcad;\n}\n\n#h1 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #98d98e;\n}\n#h2 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #c1d8ac;\n}\n#h3 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #93b69c;\n}\n\n#j1 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #98d98e;\n}\n#j2 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #c1d8ac;\n}\n#j3 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #93b69c;\n}\n\n#k1 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #c1d8ac;\n}\n#k2 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #b9d08b;\n}\n#k3 {\n  float: left;\n  width: 400px;\n  height: 120px;\n  background-color:  #badcad;\n}\n\n#m1 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #c1d8ac;\n}\n#m2 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #b9d08b;\n}\n#m3 {\n  float: left;\n  width: 400px;\n  height: 200px;\n  background-color:  #badcad;\n}\n\n.v1 {\n  clear: both;\n  height: 100px;\n  background-color:  #aacf53;\n}\n.x1 {\n  height: 100px;\n\tpadding: 20px;\n  background-color:  #c1d8ac;\n}\n.y1 {\n  background-color: #e4dc8a;\n\tpadding: 20px;\n  height: 250px;\n}\n.z1 {\n  height: 25px;\n  background-color: #8f8667;\n  font-size: 18px;\n  text-align: center;\n}\n\n</style>\n </head>\n <body style=\"background-color: #EAE5E3\">\n\n  <div id='basic'>\n\n    <div class='a1'>\n      <h2>IoT Sample Dashboard</h2>\n      IoTデータをリアルタイムで可視化します\n    </div>\n    <div class='b1'>\n      時刻\n        <span id=\"timedata\"></span>\n    </div>\n\n    <div id='d1' align=\"center\">\n      d1\n    </div>\n    <div id='d2' align=\"center\">\n      d2\n    </div>\n    <div id='d3' align=\"center\">\n      d3\n    </div>\n\n    <div id='e1' >\n      <h2 style=\"margin-left:10px;\">照度</h2>\n        <span style=\"text-align:left; font-size:18pt; margin-left:100px;\" id=\"e1data\"></span>lux\n    </div>\n    <div id='e2'>\n      <h2 style=\"margin-left:10px;\">気圧</h2>\n  \t\t\t<span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"e2data\"></span>hPa\n    </div>\n    <div id='e3'>\n        <h2 style=\"margin-left:10px;\">UV値</h2>\n    \t\t\t<span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"e3data\"></span>\n    </div>\n\n    <div id='f1' align=\"center\">\n      f1\n    </div>\n    <div id='f2' align=\"center\">\n      f2\n    </div>\n    <div id='f3' align=\"center\">\n      f3\n    </div>\n\n    <div id='h1' >\n      <h2 style=\"margin-left:10px;\">加速度(X軸)</h2>\n        <span style=\"text-align:left; font-size:18pt; margin-left:100px;\" id=\"h1data\"></span>\n    </div>\n    <div id='h2'>\n      <h2 style=\"margin-left:10px;\">加速度(Y軸)</h2>\n  \t\t\t<span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"h2data\"></span>\n    </div>\n    <div id='h3'>\n      <h2 style=\"margin-left:10px;\">加速度(Z軸)</h2>\n  \t\t\t<!--- <span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"d8data\"></span> --->\n        <span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"h3data\"></span>\n    </div>\n\n    <div id='j1' align=\"center\">\n      j1\n    </div>\n    <div id='j2' align=\"center\">\n      j2\n    </div>\n    <div id='j3' align=\"center\">\n      j3\n    </div>\n\n    <div id='k1' >\n      <h2 style=\"margin-left:10px;\">地磁気(X軸)</h2>\n        <span style=\"text-align:left; font-size:18pt; margin-left:100px;\" id=\"k1data\"></span>\n    </div>\n    <div id='k2'>\n      <h2 style=\"margin-left:10px;\">地磁気(Y軸)</h2>\n  \t\t\t<span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"k2data\"></span>\n    </div>\n    <div id='k3'>\n      <h2 style=\"margin-left:10px;\">地磁気(Z軸)</h2>\n  \t\t\t<!--- <span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"d8data\"></span> --->\n        <span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"k3data\"></span>\n    </div>\n\n    <div id='m1' align=\"center\">\n      m1\n    </div>\n    <div id='m2' align=\"center\">\n      m2\n    </div>\n    <div id='m3' align=\"center\">\n      m3\n    </div>\n\n    <div class='v1'>\n      <h2 style=\"margin-left:10px;\">アラート</h2>\n      <span style=\"text-align: left;font-size:18pt; margin-left:100px;\" id=\"alerttext\"></span>\n    </div>\n\n    <div class='x1'>\n      <!--- m1 --->\n    </div>\n\n<div class=\"y1\">\n  参考URL\n  <ul>\n    <li><a href=\"http://qiita.com/egplnt/items/af867711a7191923b2ff\">Watson IoT Platformを使ってみる</a></li>\n    <li><a href=\"https://internetofthings.ibmcloud.com/#/\">Watson IoT Platform</a></li>\n    <li><a href=\"https://developer.ibm.com/recipes/tutorials/use-the-simulated-device-to-experience-the-iot-foundation/\">Recipe - Simulator</a></li>\n  </ul>\n  マニュアル\n  <ul>\n    <li><a href=\"http://ibm.com/iot\">IBM IoT</a></li>\n    <li><a href=\"https://docs.internetofthings.ibmcloud.com/ja/\">Watson IoT Platform資料ページ</a></li>\n    <li><a href=\"https://developer.ibm.com/recipes/\">Recipe</a></li>\n  </ul>\n</div>\n\n<div class=\"z1\">\n\tcopyright (c) abc.com All right reserved.\n</div>\n</div>\n\n\n<script>\nvar c2alert0 = 0, c2alert1 = 0, c2alert2 = 0, c2alert3 = 0, c2alert4 = 0, c2alert5 = 0, c2alert6 = 0;\nvar connection = new WebSocket('wss://このIoTアプリの名前.mybluemix.net/wss/flow56a');\n\nconnection.onopen = function () {\n  console.log(\"websocket connected\");\n};\n\n// Log errors\nconnection.onerror = function (error) {\n  console.log('WebSocket Error ' + error);\n};\n\n// Log messages from the server\nconnection.onmessage = function (m) {\n  //console.log('Server: ' + m.data);\n\tdoIt(m);\n};\n\n// ゲージとラインチャートを準備\n// ラインチャートのAPIは https://developers.google.com/chart/interactive/docs/reference\n//\ngoogle.load('visualization', '1', {packages:['gauge', 'corechart']});\ngoogle.setOnLoadCallback(drawChart);\n\nfunction drawChart() {\n\td1GaugeData = google.visualization.arrayToDataTable([\n\t\t['Label', 'Value'],\n\t\t['照度', 0]\n\t]);\n  d1GaugeOptions = {\n\t\twidth: 500, height: 150,\n\t\tmin: 0, max: 500,\n\t\tyellowFrom:300, yellowTo: 400,\n    redFrom: 400, redTo: 500,\n\t\tminorTicks: 5\n\t};\n  d1Gauge = new google.visualization.Gauge(document.getElementById('d1'));\n\td1Gauge.draw(d1GaugeData, d1GaugeOptions);\n\n  d2GaugeData = google.visualization.arrayToDataTable([\n\t\t['Label', 'Value'],\n\t\t['気圧', 0]\n\t]);\n  d2GaugeOptions = {\n\t\twidth: 500, height: 150,\n\t\tmin: 1002.75, max: 1003.35,\n\t\tyellowFrom: 1002.9, yellowTo: 1003.05,\n    redFrom: 1002.75, redTo: 1002.9,\n\t\tminorTicks: 5\n\t};\n  d2Gauge = new google.visualization.Gauge(document.getElementById('d2'));\n\td2Gauge.draw(d2GaugeData, d2GaugeOptions);\n\n  d3GaugeData = google.visualization.arrayToDataTable([\n\t\t['Label', 'Value'],\n\t\t['UV値', 0]\n\t]);\n  d3GaugeOptions = {\n\t\twidth: 500, height: 150,\n\t\tmin: -1, max: 1,\n\t\tyellowFrom: 0, yellowTo: 0.5,\n    redFrom: 0.5, redTo: 1,\n\t\tminorTicks: 5\n\t};\n  d3Gauge = new google.visualization.Gauge(document.getElementById('d3'));\n\td3Gauge.draw(d3GaugeData, d3GaugeOptions);\n\n  f1ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"照度\"],['10:00:00',300]] );\n  f1ChartData.removeRow(0);\n  f1ChartOptions = { title: '照度',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#c1d8ac' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  f1Chart = new google.visualization.LineChart(document.getElementById('f1'));\n  f1Chart.draw(f1ChartData, f1ChartOptions);\n\n  f2ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"気圧\"],['10:00:00',300]] );\n  f2ChartData.removeRow(0);\n  f2ChartOptions = { title: '気圧',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#b9d08b' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  f2Chart = new google.visualization.LineChart(document.getElementById('f2'));\n  f2Chart.draw(f2ChartData, f2ChartOptions);\n\n  f3ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"UV値\"],['10:00:00',300]] );\n  f3ChartData.removeRow(0);\n  f3ChartOptions = { title: 'UV値',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#badcad' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  f3Chart = new google.visualization.LineChart(document.getElementById('f3'));\n  f3Chart.draw(f3ChartData, f3ChartOptions);\n\n  j1ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(X軸)\"],['10:00:00',3]] );\n  j1ChartData.removeRow(0);\n  j1ChartOptions = { title: '加速度(X軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#98d98e' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j1Chart = new google.visualization.LineChart(document.getElementById('j1'));\n  j1Chart.draw(j1ChartData, j1ChartOptions);\n\n  j2ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(Y軸)\"],['10:00:00',3]] );\n  j2ChartData.removeRow(0);\n  j2ChartOptions = { title: '加速度(Y軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#c1d8ac' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j2Chart = new google.visualization.LineChart(document.getElementById('j2'));\n  j2Chart.draw(j2ChartData, j2ChartOptions);\n\n  j3ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(Z軸)\"],['10:00:00',3]] );\n  j3ChartData.removeRow(0);\n  j3ChartOptions = { title: '加速度(Z軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#93b69c' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j3Chart = new google.visualization.LineChart(document.getElementById('j3'));\n  j3Chart.draw(j3ChartData, j3ChartOptions);\n\n  j1ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(X軸)\"],['10:00:00',3]] );\n  j1ChartData.removeRow(0);\n  j1ChartOptions = { title: '加速度(X軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#98d98e' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j1Chart = new google.visualization.LineChart(document.getElementById('j1'));\n  j1Chart.draw(j1ChartData, j1ChartOptions);\n\n  j2ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(Y軸)\"],['10:00:00',3]] );\n  j2ChartData.removeRow(0);\n  j2ChartOptions = { title: '加速度(Y軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#c1d8ac' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j2Chart = new google.visualization.LineChart(document.getElementById('j2'));\n  j2Chart.draw(j2ChartData, j2ChartOptions);\n\n  j3ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"加速度(Z軸)\"],['10:00:00',3]] );\n  j3ChartData.removeRow(0);\n  j3ChartOptions = { title: '加速度(Z軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#93b69c' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  j3Chart = new google.visualization.LineChart(document.getElementById('j3'));\n  j3Chart.draw(j3ChartData, j3ChartOptions);\n\n  m1ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"地磁気(X軸)\"],['10:00:00',3]] );\n  m1ChartData.removeRow(0);\n  m1ChartOptions = { title: '地磁気(X軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#c1d8ac' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  m1Chart = new google.visualization.LineChart(document.getElementById('m1'));\n  m1Chart.draw(m1ChartData, m1ChartOptions);\n\n  m2ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"地磁気(Y軸)\"],['10:00:00',3]] );\n  m2ChartData.removeRow(0);\n  m2ChartOptions = { title: '地磁気(Y軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#b9d08b' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  m2Chart = new google.visualization.LineChart(document.getElementById('m2'));\n  m2Chart.draw(m2ChartData, m2ChartOptions);\n\n  m3ChartData = google.visualization.arrayToDataTable(\n    [[\"時刻\",\"地磁気(Z軸)\"],['10:00:00',3]] );\n  m3ChartData.removeRow(0);\n  m3ChartOptions = { title: '地磁気(Z軸)',\n    legend: { position: 'bottom' },\n    backgroundColor: {stroke:'#badcad' ,strokeWidth:10, fill:'#ffffff'}\n  };\n  m3Chart = new google.visualization.LineChart(document.getElementById('m3'));\n  m3Chart.draw(m3ChartData, m3ChartOptions);\n\n};\n\n//websocketからの毎秒のデータを受信してゲージ・チャートへ表示する\nfunction doIt(msg){\n  console.log(\"doit:\" + msg.data);\n\tvar msgs = JSON.parse(msg.data);\n\n  // msgs[3]は二重配列なので\"msgs[3][0]\"で温度の値を取り出してリアルタイム表示する\n  d1GaugeData = google.visualization.arrayToDataTable([\n    ['Label', 'Value'],\n    ['照度', msgs[4][0]]\n  ]);\n  d1Gauge.draw(d1GaugeData, d1GaugeOptions);\n  console.log(\"msgs[4][0] = \" + msgs[4][0]);\n\n  d2GaugeData = google.visualization.arrayToDataTable([\n    ['Label', 'Value'],\n    ['気圧', msgs[9][0]]\n  ]);\n  d2Gauge.draw(d2GaugeData, d2GaugeOptions);\n\n  d3GaugeData = google.visualization.arrayToDataTable([\n    ['Label', 'Value'],\n    ['UV値', msgs[10][0]]\n  ]);\n  d3Gauge.draw(d3GaugeData, d3GaugeOptions);\n\n  f1ChartData.addRow( [ msgs[0][0], msgs[4][0] ] );\n  if ( f1ChartData.getNumberOfRows() > 9) {\n    f1ChartData.removeRow(0);\n  }\n  f1Chart.draw(f1ChartData, f1ChartOptions);\n\n  f2ChartData.addRow( [ msgs[0][0], msgs[9][0] ] );\n  if ( f2ChartData.getNumberOfRows() > 9) {\n    f2ChartData.removeRow(0);\n  }\n  f2Chart.draw(f2ChartData, f2ChartOptions);\n\n  f3ChartData.addRow( [ msgs[0][0], msgs[10][0] ] );\n  if ( f3ChartData.getNumberOfRows() > 9) {\n    f3ChartData.removeRow(0);\n  }\n  f3Chart.draw(f3ChartData, f3ChartOptions);\n\n  j1ChartData.addRow( [ msgs[0][0], msgs[1][0] ] );\n  if ( j1ChartData.getNumberOfRows() > 9) {\n    j1ChartData.removeRow(0);\n  }\n  j1Chart.draw(j1ChartData, j1ChartOptions);\n\n  j2ChartData.addRow( [ msgs[0][0], msgs[2][0] ] );\n  if ( j2ChartData.getNumberOfRows() > 9) {\n    j2ChartData.removeRow(0);\n  }\n  j2Chart.draw(j2ChartData, j2ChartOptions);\n\n  j3ChartData.addRow( [ msgs[0][0], msgs[3][0] ] );\n  if ( j3ChartData.getNumberOfRows() > 9) {\n    j3ChartData.removeRow(0);\n  }\n  j3Chart.draw(j3ChartData, j3ChartOptions);\n\n  m1ChartData.addRow( [ msgs[0][0], msgs[5][0] ] );\n  if ( m1ChartData.getNumberOfRows() > 9) {\n    m1ChartData.removeRow(0);\n  }\n  m1Chart.draw(m1ChartData, m1ChartOptions);\n\n  m2ChartData.addRow( [ msgs[0][0], msgs[6][0] ] );\n  if ( m2ChartData.getNumberOfRows() > 9) {\n    m2ChartData.removeRow(0);\n  }\n  m2Chart.draw(m2ChartData, m2ChartOptions);\n\n  m3ChartData.addRow( [ msgs[0][0], msgs[6][0] ] );\n  if ( m3ChartData.getNumberOfRows() > 9) {\n    m3ChartData.removeRow(0);\n  }\n  m3Chart.draw(j3ChartData, m3ChartOptions);\n\n  target = document.getElementById(\"timedata\");\n\ttarget.innerHTML = msgs[0];\n  target = document.getElementById(\"e1data\"); // 照度 e1に表示\n\ttarget.innerHTML = msgs[4];\n  target = document.getElementById(\"e2data\"); // 気圧 e2に表示\n\ttarget.innerHTML = msgs[9];\n  target = document.getElementById(\"e3data\"); // UV値 e3に表示\n\ttarget.innerHTML = msgs[10];\n  target = document.getElementById(\"h1data\"); // X軸加速度 h1に表示\n\ttarget.innerHTML = msgs[1];\n  target = document.getElementById(\"h2data\"); // Y軸加速度 h2に表示\n\ttarget.innerHTML = msgs[2];\n  target = document.getElementById(\"h3data\"); // Z軸加速度 h3に表示\n\ttarget.innerHTML = msgs[3];\n  target = document.getElementById(\"k1data\"); // X軸地磁気 k1に表示\n\ttarget.innerHTML = msgs[5];\n  target = document.getElementById(\"k2data\"); // Y軸地磁気 k2に表示\n\ttarget.innerHTML = msgs[6];\n  target = document.getElementById(\"k3data\"); // Z軸地磁気 k3に表示\n\ttarget.innerHTML = msgs[7];\n\n};\n\n</script>\n\n</body>\n</html>\n","x":350,"y":120,"wires":[["5a3d7174.4f3d2"]]},{"id":"5a3d7174.4f3d2","type":"http response","z":"89d26c8f.7f48a","name":"","x":530,"y":120,"wires":[]},{"id":"a4d38e03.282f7","type":"http in","z":"89d26c8f.7f48a","name":"","url":"/test56a","method":"get","swaggerDoc":"","x":150,"y":120,"wires":[["ed8f0bb.cd5e278"]]},{"id":"e0a37e68.f707c8","type":"comment","z":"89d26c8f.7f48a","name":"Alpsシミュレータからの表示","info":"","x":180,"y":80,"wires":[]}]

#参考情報

  1. スコット・マレイさんのD3チュートリアル
3
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?