X-Git-Url: https://git.toastfreeware.priv.at/chrisu/seepark.git/blobdiff_plain/081052516499e0c845c9364342c75b87dc204ad5..26256314244db4e501c6514d46ee65b88d65675c:/seewasser.py diff --git a/seewasser.py b/seewasser.py index a65d8c7..7b58c05 100755 --- a/seewasser.py +++ b/seewasser.py @@ -1,13 +1,19 @@ #! /usr/bin/python3 +import argparse import logging import datetime +import time import re import sys import csv import os import configparser from sqlalchemy import create_engine +import warnings +import MySQLdb.cursors + +logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) #May 27 21:32 /sys/bus/w1/devices/28-0416a1bab9ff #May 27 21:33 /sys/bus/w1/devices/28-0416a1ac66ff @@ -51,14 +57,24 @@ def readsensor(sensor_id): return jetzt, temp_raw, temp +def read_buggy_sensor(sensor_id): + for i in range(120): + jetzt, temp_raw, temp = readsensor(sensor_id) + if temp < 30: + return jetzt, temp_raw, temp + time.sleep(1) + raise ReadsensorError('Zu hoch') def writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value): # Schreiben des csv-files - file = open(config.get("csv", "filename"), "a", newline = "") - writer = csv.writer(file, dialect = "excel") - writer.writerow([timestamp.strftime("%Y-%m-%d %H:%M"), sensor_id, "{:.1f}".format(value)]) + with open(os.path.expanduser(config.get("csv", "filename")), "a", newline = "") as file: + writer = csv.writer(file, dialect = "excel") + writer.writerow([timestamp.strftime("%Y-%m-%d %H:%M"), sensor_id, sensor_name, "{:.1f}".format(value)]) - file.close() + +def readcsvfile(csvfile): + with open(csvfile, "r", newline="") as file: + yield from csv.DictReader(file, dialect = "excel", fieldnames=("timestamp", "sensor_id", "sensor_name", "value")) def writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value): @@ -68,22 +84,51 @@ def writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, val host = config.get('database','hostname') db = config.get('database','database') - engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=True) + engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False) conn = engine.connect() - conn.execute("insert into sensors (sensor_id, sensor_name, value_type, value_raw, value, timestamp) values (?,?,?,?,?,?)", sensor_id, sensor_name, value_type, value_raw, value, timestamp) + with warnings.catch_warnings(): + # ignore _mysql_exceptions.Warning: Duplicate entry '0316a2193bff-2018-08-29 14:30:00' for key 'sensorid_timestamp' + warnings.simplefilter("ignore", category=MySQLdb.cursors.Warning) + if args.verbose: + logging.info("Writing to database: sensor_id={}, sensor_name={}, value_type={}, value_raw={}, value={}, timestamp={}".format(sensor_id, sensor_name, value_type, value_raw, value, timestamp)) + conn.execute("insert ignore into sensors (sensor_id, sensor_name, value_type, value_raw, value, timestamp) values (%s,%s,%s,%s,%s,%s)", sensor_id, sensor_name, value_type, value_raw, value, timestamp) conn.close() -def main(): +def process_csv_file(config, fromcsvfile, value_type, sensors): + # "timestamp", "sensor_id", "sensor_name", "value" + sensors_ids = [sensor_id for sensor_id, sensor_name in sensors] + for record in readcsvfile(fromcsvfile): + timestamp, sensor_id, sensor_name, value = (record["timestamp"], record["sensor_id"], record["sensor_name"], float(record["value"])) + if sensor_id in sensors_ids: + value_raw = None + writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value) + + +def main(configfile, fromcsvfile): config = configparser.ConfigParser() - config.read(os.path.expanduser('~/seewasser.ini')) - + config.read(configfile) + sensors = config.items('temperature') value_type = "Wassertemperatur" - for sensor_id, sensor_name in config.items('temperature'): - timestamp, value_raw, value = readsensor(sensor_id) + + if fromcsvfile: + process_csv_file(config, fromcsvfile, value_type, sensors) + return + + for sensor_id, sensor_name in sensors: + timestamp, value_raw, value = read_buggy_sensor(sensor_id) writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value) writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value) - logging.info('Sensor {}: {:.1f}°C'.format(sensor_id, value)) + if args.verbose: + logging.info('Sensor {}: {:.1f}°C'.format(sensor_id, value)) + +if __name__ == '__main__': + default_config_file = os.path.expanduser('~/seewasser.ini') + parser = argparse.ArgumentParser(description='Read sensor data') + parser.add_argument('--config', default=default_config_file, help='configuration file') + parser.add_argument('--fromcsvfile', help='write values from csv file to database') + parser.add_argument("--verbose", help='write some output', action='store_true') + args = parser.parse_args() + main(args.config, args.fromcsvfile) -main()