0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

データーロガー

Last updated at Posted at 2025-08-20

おうちの気温は以下の仕組みでグラフにしています。

datalog1.png

この仕組みの場合新たにデータをとり始めてグラフにするにはSQLite3のテーブルが必要になります。

ちょっと試しにとかが、やりにくいです。

いろいろ考えて以下の方法を作ってみました。

datalog2.png

処理の流れは、データを取って60秒スリープしてを繰り返して、時間が変わったら、平均してjsonのデータを作り過去のデーターに追加してhttpサーバにレスポンスを設定しています。mruby on YABMではfloatが使えないので、整数で処理をしています。

以下のような動作になります。

c1k: {2} curl -I http://10.0.1.123:8080/
HTTP/1.1 200 OK
Content-type: application/json
Access-Control-Allow-Origin: *
Content-Length: 211
Connection: close

c1k: {3} curl http://10.0.1.123:8080/
[{"time":"082009","temp":30.6},{"time":"082010","temp":30.7},{"time":"082011","temp":31.4},{"time":"082012","temp":31.9},{"time":"082013","temp":31.9},{"time":"082014","temp":32.1},{"time":"082015","temp":32.4}]

jsonをどこからでもアクセスできるようにAccess-Control-Allow-Originヘッダーを設定してあります。

これをChart.js(V2)でグラフにします

<html>
<head>
</head>
<body>
<script src="http://10.0.1.18/js/Chart.min.js"></script>
<script src="http://10.0.1.18/js/jquery.min.js"></script>
<canvas id="myChart" width="200" height="100"></canvas>
<script>
var ctx = document.getElementById("myChart");
var clab = [];
var cdat = [];
var bg = [];
var bd = [];
$(function() {
  if(!window.CanvasRenderingContext2D){
    return;
  }
  $.getJSON("http://10.0.1.123:8080/" , function(data) {
    var
      len = data.length;

    for(var i = 0; i < len; i++) {
      clab.push(data[i].time);
      cdat.push(data[i].temp);
    }

    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: clab,
            datasets: [{
                label: 'Temperature',
                data: cdat,
                fill: false,
                borderColor: "red"
            }]
        },
        options: {
          tooltips: {
            callbacks: {
              label: function (tooltipItem, data) {
                return data.datasets[0].data[tooltipItem.index]
                  + " c";
              }
            }
          }
        }
    });
  });
});
</script>
</body>
</html>

便宜的にHTMLやJavaScriptのファイルはサーバの上においてますが、すべてのファイルをPCに置いても動作します。

image.png

BMP180の気温のコードになっていますが、ちょっと作り変えれば別の用途でも使えると思います。

しばらく動かして様子を見たいと思います。

時間は起動時に一回合わせただけなので、時間がたつと狂います。定期的に時間合わせたほうがいいです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?