Add /api/<version>/sensor/<sensor_id>.
[chrisu/seepark.git] / seewasser.py
index a17e794cf9b38da1992cdee5ab3fa14fb77469bf..dfed1cfa06e6fa6379045aa8fe0d9e4758936456 100755 (executable)
@@ -1,10 +1,13 @@
 #! /usr/bin/python3
 
+import logging
 import datetime
 import re
 import sys
 import csv
 import os
+import configparser
+from sqlalchemy import create_engine
 
 #May 27 21:32 /sys/bus/w1/devices/28-0416a1bab9ff
 #May 27 21:33 /sys/bus/w1/devices/28-0416a1ac66ff
@@ -16,8 +19,12 @@ import os
 # einen Sensor auslesen
 #/sys/bus/w1/devices/
 
-def readsensor(sensorID):
-    sensorfile = "/sys/bus/w1/devices/28-{}/w1_slave".format(sensorID)
+class ReadsensorError(RuntimeError):
+    pass
+    
+    
+def readsensor(sensor_id):
+    sensorfile = "/sys/bus/w1/devices/28-{}/w1_slave".format(sensor_id)
     file = open(sensorfile)
 
     # Inhalt des Sensors:
@@ -30,40 +37,53 @@ def readsensor(sensorID):
 
     yesno = match.group(1)
     if yesno != "YES":
-        return None
+        raise ReadsensorError('Could not evaluate sensorfile "{}"'.format(sensorfile))
         
     # Temperatur raus
     linetemp = file.readline()
     match = re.search(" t=([-0-9]+)",linetemp)
 
-    temp = match.group(1)
-    temp = float(temp)/1000
+    temp_raw = match.group(1)
+    temp = float(temp_raw)/1000
 
     file.close()
-
     jetzt = datetime.datetime.now()
-    # print(jetzt)
 
+    return jetzt, temp_raw, temp
+
+
+def writesensordatacsv(config, sensor_id, sensor_name, timestamp, value_type, value_raw, value):
     # Schreiben des csv-files
-    file2 = open("badesaison.csv", "a", newline = "")
-    writer = csv.writer(file2, dialect = "excel")
-    writer.writerow([jetzt.strftime("%Y-%m-%d %H:%M"), sensorID, "{:.1f}".format(temp)])
+    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, sensor_name, "{:.1f}".format(value)])
+
+    file.close()
 
-    file2.close()
 
-    # Nur für die Ausgabe wird gerundet
-    return temp
+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')
     
-sensoren = ["0416a1bab9ff","0416a1ac66ff","0516a207a4ff","0316a2193bff","0316a21383ff"]
+    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 (%s,%s,%s,%s,%s,%s)", sensor_id, sensor_name, value_type, value_raw, value, timestamp)
+    conn.close()
 
-error = False
 
-for sensorID in sensoren:
-    temp = readsensor(sensorID)
-    if temp is None:
-        print("Fehler bei Sensor{}".format(sensorID))
-        error = True
-    else:
-        print('Sensor {}: {:.1f}°C'.format(sensorID,temp))
+def main():
+    config = configparser.ConfigParser()
+    config.read(os.path.expanduser('~/seewasser.ini'))
+    
+    value_type = "Wassertemperatur"
+    for sensor_id, sensor_name in config.items('temperature'):
+        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))
+
 
-sys.exit(1 if error else 0)
\ No newline at end of file
+main()