温度測定を題材にラズパイIoTシステムの「収集」「蓄積」「活用」を理解するラズパイで製造業のお手軽IoT活用(2)(4/4 ページ)

» 2020年04月27日 10時00分 公開
前のページへ 1|2|3|4       
※本記事はアフィリエイトプログラムによる収益を得ています

記事に使用したサンプルソースのテキスト

import glob
import time
import subprocess
import sqlite3
import threading
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
db_file = '/home/pi/MTS/temperature.sqlite3'
def read_temp_raw():
 catdata = subprocess.Popen(['cat',device_file], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
 out, err = catdata.communicate()
 out_decode = out.decode('utf-8')
 lines = out_decode.split('\n')
 return lines
def read_temp():
 lines = read_temp_raw()
 if lines[0].strip()[-3:] != 'YES':
  return False
 equals_pos = lines[1].find('t=')
 temp_string = lines[1][equals_pos + 2:]
 temp_c = float(temp_string) / 1000.0
 return temp_c
def save_temp():
 try:
  connection = sqlite3.connect(db_file)
  cursor = connection.cursor()
  temp = read_temp()
  if temp:
   cursor.execute("INSERT INTO DATE_TEMPERATURE VALUES (strftime('%Y/%m/%d', date('now', 'localtime')), strftime('%H:%M:%S',time('now', 'localtime')), ?);", (temp,))
   connection.commit()
 except:
  connection.rollback()
 finally:
  connection.close()
while True:
 th = threading.Thread(target=save_temp)
 th.start()
 time.sleep(3)
リスト1 「mt.py」のサンプルソースコード
<?php
 $dataNum = 180;
 $check = false;
 while ($check == false) {
  try {
   $db = new SQLite3("/home/pi/MTS/temperature.sqlite3", SQLITE3_OPEN_READONLY);
   $date = date("Y/m/d");
   $sql = "select * from DATE_TEMPERATURE where DATE = '" . $date . "' order by TIME desc limit " . $dataNum . ";";
   $res = $db->query($sql);
   $i = 0;
   while ($t = $res->fetchArray(SQLITE3_NUM)) {
    $b[$i] = $t;
    $i += 1;
   }
   for ($k = 0; $k < $dataNum - $i; $k++) {
    $a[$k][0] = $a[$k][1] = "";
    $a[$k][2] = "null";
   }
   for ($k = 0; $k < $i; $k++) {
    $a[$dataNum - $i + $k] = $b[$i - $k - 1];
   }
   $check = true;
  } catch (Exception $e) {
   $i = 0;
   $check = false;
   usleep(10000);
  } finally {
   $db->close();
   $db = null;
  }
 }
 $str = "[";
 for ($k = 0; $k < $dataNum; $k++) {
  $str .= "'" . $a[$k][1] . "'," . $a[$k][2] . ",";
 }
 $str .= "]";
 echo $str;
?>
リスト2 「jsonTemps.php」のサンプルソースコード
  <script>
   var today = new Date();
   var date = '' + today.getFullYear() + ('00' + (today.getMonth() + 1)).substr(-2) + ('00' + today.getDate()).substr(-2);
   var xhr
   var xhr2;
   var times = new Array();
   var temps = new Array();
   var ctx;
   var chart;
   var color;
   onload = function(){
    ctx = document.getElementById('temp').getContext('2d');
    updateGraph();
    setInterval(updateGraph, 1000);
   }
   function updateGraph(){
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = myupdate;
    xhr.open("GET", "jsonTemps.php?date=" + date);
    xhr.send(null);
   }
   function myupdate(){
    if (xhr.readyState == 4 && xhr.status == 200) {
     list = eval('(' + xhr.responseText + ')');
     for (var i = 0; i < list.length / 2; i++) {
      times[i] = list[2 * i];
      temps[i] = list[2 * i + 1];
     }
     drawChart();
    }
   }
   
   function startMt(){
    xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "startMt.php");
    xhr2.send(null);
   }
  function stopMt(){
   xhr2 = new XMLHttpRequest();
   xhr2.open("GET", "stopMt.php");
   xhr2.send(null);
  }
  </script>
  <script>
   function drawChart() {
    if (typeof chart != 'undefined') chart.destroy();
    color = "rgb(100, 200, 200)";
    chart = new Chart(ctx, {
     type: "line",
     data: {
      labels: times,
      datasets: [{
       label: "温度",
       lineTension: 0,
       fill: false,
       backgroundColor: color,
       borderColor: color,
       data: temps,
      }]
     },
     options: {
      responsive: false,
      animation: false,
      scales: {
       xAxes: [{
        scaleLabel: {
         display: true,
         labelString: date
        }
       }],
       yAxes: [{
        scaleLabel: {
         display: true,
         labelString: "温度(℃)"
        },
        ticks: {
         min: -20,
         max: 120
        }
       }]
      }
     }
    });
   }
  </script>
リスト3 「latest.html」のサンプルソースコード


前のページへ 1|2|3|4       

Copyright © ITmedia, Inc. All Rights Reserved.