アメグラ2号のブログ

1980年代後半の古き良きビデオゲームのほか、オッサンの個人的備忘録

ラズパイ 温度測定データをDBへ格納

f:id:game-allergy:20210416130714j:plain

前回はpythonのWEBスクレイピングで気象情報を取得、気温・湿度のグラフを作成するところまでやった。
そうだ、今度はラズパイの温度計測データと比較してみよう。WEBから得られる気温・湿度の情報と、自宅内の実際の気温とを比較・・・つまり、他から得た情報、自分で採取した情報、この2つに乖離がないか?(あるわけないけど)ということを調査する・・・自分で取得したデータっていうところが今回のキモだ。電子工作をするなら自分でデバイスをいじってデータを取得してみたいよね。あと、python にも慣れてきたからスクリプトを書くのが楽しいってのもあるか。

f:id:game-allergy:20210416130740j:plain

ラズパイ内のpythonに追加したモジュールは、schedule, sqlite3, datetime

◆DB/テーブル作成

# ===================================
# 特定DBのテーブル有無確認後、作成しなおす
# ===================================
import sqlite3

# DB接続、カーソル起動
connection = sqlite3.connect('TEST.db')
cur = connection.cursor()

# ===================================
def CheckTableExistence():
    cur.execute('SELECT COUNT(*) FROM sqlite_master WHERE TYPE="table" AND NAME="HIH6130"')

def CreateTable():
    sql = 'CREATE TABLE HIH6130(id INTEGER PRIMARY KEY AUTOINCREMENT, temp INTEGER, humid INTEGER, time STRING)'
    cur.execute(sql)

def DropTable():
    sql = 'DROP TABLE HIH6130'
    cur.execute(sql)
# ===================================
#テーブル存在確認
CheckTableExistence()

if cur.fetchone() == (0,): #存在しないとき
    print("Table is not existed then created")
    #テーブルがなかったら作成する
    CreateTable()
    
else:
    print('Table exists, then deleted old one and created new one')
    #テーブルがあったら削除する
    DropTable()
    CreateTable()

connection.commit()
connection.close()
# ===================================
print('--------------------')
print('Check table; end of line')

個人的な印象だけど、sqlite3ってすごーいラクチン。さすがアプリケーション内のモジュールだ。MariaDBみたいに別サーバだと接続がちょっとややこしい。個人で軽い検証程度ならsqliteで十分だね。

◆気温・湿度の取得、DBへ格納

#! /usr/bin/env python3

import time
import datetime
import smbus
import schedule
import sqlite3

i2c_channel = 1
i2c = smbus.SMBus( i2c_channel )

def job():
    Measure()

def Measure():
   
    # Measurement
    for i in range(0,5,1):

        i2c.write_quick(0x27)
        time.sleep(0.1)

        dac = i2c.read_i2c_block_data( 0x27, 0, 4 )

        h = ( ( dac[0] & 0x3f ) << 8 ) | dac[1]
        humi = (float)(h) / 16383 * 100

        t = ( dac[2] << 6 ) | (dac[3] >> 2)
        temp = (float)(t) /16383 * 165 - 40

        now1 = datetime.datetime.now()
        now2 = now1.strftime('%Y-%m-%d %H:%M:%S')

        # Get them into DB
        dbregist(temp,humi,now2)

        # Show the data on Display (for checking)
        print ( "Time        : %s    " % now2  )
        print ( "Temperature : %.2f C" % temp  )
        print ( "Humidity    : %.2f %%" % humi )
        print ( "---------   : ")

        time.sleep(1)

def dbregist(t,h,now2):
    dbname = 'TEST.db'
    connection = sqlite3.connect(dbname)

    cur = connection.cursor()
    sql1 = 'INSERT INTO HIH6130(temp, humid, time) VALUES(?,?,?)'
    cur.execute(sql1,(t, h, now2))

    connection.commit()
    cur.close()
    connection.close()

    print('--------------------')
    print('DB; end of line')

# Do Job for a certain period of time
schedule.every(10).seconds.do(job)

# Wait until Doing Job
while True:
    schedule.run_pending()
    time.sleep(1)

◆DB内容を読み込んでディスプレイに出力

#! /usr/bin/env python3
import sqlite3
#import pandas as pd
#import matplotlib.pyplot as plt


dbname = 'TEST.db'
connection = sqlite3.connect(dbname)
cur = connection.cursor()

sql3 = 'SELECT temp, humid, time FROM HIH6130'
c3 = cur.execute(sql3)
result3 = c3.fetchall()
print(result3)

"""
df1 = pd.DataFrame(result1,columns=["temp"])
df2 = pd.DataFrame(result2,columns=["humid"])

pd.set_option("display.max_colwidth", None)
pd.set_option("display.max_rows", None)

#print(df1)
#print(df2)
"""

cur.close()
connection.close()

print('--------------------')
print('SeeDB; end of line')

◆実行結果(データ取得、DB書き込み)

f:id:game-allergy:20210416125517j:plain

実際には1時間ごとにデータを取得して24個のデータをグラフ化する…ということをしたい。が、データ取得のテストなので10秒ごとに5回分のデータを取得するようにしている。scheduleモジュールもしっかり動いてるし問題なさそう。

◆実行結果(DB情報の読み出し)

f:id:game-allergy:20210416125607j:plain

pandasで書き出そうとしたんだけど、なんかうまくいかない。なんかmoduleの読込でおかしい。なので、今回は単にDBからデータの吐き出しまで。ほんとはここからMatplotでのグラフ書き出しをしようかと思っていたけど、pandasで詰まってしまいそこまで到達していない。


◆4/19追記。pandas解決

game-allergy.hatenablog.com