From 22e0a32c785477a977f8717b819ecaa9c27d61fb Mon Sep 17 00:00:00 2001 From: Mark Powers Date: Sat, 27 Nov 2021 23:08:27 +0000 Subject: Convert weather script to save to DB --- weather_oneline.py | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/weather_oneline.py b/weather_oneline.py index 745d37d..0b720ba 100644 --- a/weather_oneline.py +++ b/weather_oneline.py @@ -1,13 +1,36 @@ import board import busio import digitalio -import adafruit_bme280 +from adafruit_bme280 import basic as adafruit_bme280 import datetime +import mysql.connector +import configparser i2c = busio.I2C(board.SCL, board.SDA) bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c) -temp_c = bme280.temperature -temp_f = temp_c * 9 / 5 + 32 -response = "%s,%0.1f,%0.1f,%0.1f" % (datetime.datetime.now(), temp_f, bme280.humidity, bme280.pressure) -print(response) +config = configparser.ConfigParser() +config.read("/etc/weather.ini") + +db = mysql.connector.connect( + host=config["database"]["host"], + user=config["database"]["user"], + password=config["database"]["password"], + database=config["database"]["database"], +) + +def get_reading(): + temp_c = bme280.temperature + temp_f = temp_c * 9 / 5 + 32 + return (datetime.datetime.now(), temp_f, bme280.humidity, bme280.pressure) + +def insert(table, timestamp, value): + cursor = db.cursor() + timestamp = timestamp.strftime('%Y-%m-%d %H:%M:%S') + cursor.execute(f"insert into {table} (timestamp, value) values ('{timestamp}', '{value}')") + +timestamp, temperature, humidity, pressure = get_reading() +insert("temperature", timestamp, temperature) +insert("pressure", timestamp, pressure) +insert("humidity", timestamp, humidity) +db.commit() -- cgit v1.2.3