+def writesensordatadb(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value):
+ # Schreiben des db-files
+ user = config.get('database', 'user')
+ pwd = config.get('database','password')
+ host = config.get('database','hostname')
+ db = config.get('database','database')
+
+ engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
+ conn = engine.connect()
+ 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)
+ 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 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(configfile)
+ sensors = config.items('temperature')
+ value_type = "Wassertemperatur"
+
+ if fromcsvfile:
+ process_csv_file(config, fromcsvfile, value_type, sensors)
+ return
+
+ for sensor_id, sensor_name in sensors:
+ timestamp, value_raw, value = readsensor(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 __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')
+ args = parser.parse_args()
+ main(args.config, args.fromcsvfile)