show current/most recent air/water temperature on top of page
authorgregor herrmann <gregor@toastfreeware.priv.at>
Sat, 16 Jun 2018 17:56:35 +0000 (19:56 +0200)
committergregor herrmann <gregor@toastfreeware.priv.at>
Sat, 16 Jun 2018 17:56:35 +0000 (19:56 +0200)
web/seepark_web.py
web/static/seepark_web.css
web/templates/seepark_web.html

index 9ad59f1..ce4347f 100644 (file)
@@ -6,6 +6,7 @@ import os
 from flask import Flask, render_template, jsonify, request
 import flask.json
 from sqlalchemy import create_engine
+import requests
 
 
 class JSONEncoder(flask.json.JSONEncoder):
@@ -24,6 +25,7 @@ app.json_encoder = JSONEncoder
 config = configparser.ConfigParser()
 config.read(os.environ['SEEPARKINI'])
 apikey = config.get('openweathermap', 'apikey')
+cityid = config.get('openweathermap', 'cityid')
 
 
 def open_engine(config):
@@ -94,6 +96,29 @@ def select_sensordata(initial_where, initial_sql_args):
     return result
 
 
+def currentairtemperature(apikey, cityid):
+    baseurl = 'http://api.openweathermap.org/data/2.5/weather'
+    query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
+    try:
+        response = requests.get(query)
+        if response.status_code != 200:
+            response = 'N/A'
+            return response, datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
+        else:
+            weatherdata = response.json()
+            return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt']).strftime('%Y-%m-%d %H:%M')
+    except requests.exceptions.RequestException as error:
+        print (error)
+
+
+def currentwatertemperature(sensorid):
+    engine = open_engine(config)
+    with engine.connect() as conn:
+        cursor = conn.execute('select value, timestamp from sensors where sensor_id=%s order by timestamp desc limit 1', sensorid)
+        result = [dict(row) for row in cursor]
+        return result[0]['value'], result[0]['timestamp'].strftime('%Y-%m-%d %H:%M')
+
+
 @app.route('/api/<version>/sensors/')
 def sensors(version):
     """List all sensors found in the database"""
@@ -164,5 +189,16 @@ def data(timespan):
 
 @app.route("/")
 def index():
-    return render_template('seepark_web.html', apikey=apikey)
-
+    airvalue, airtime     = currentairtemperature(apikey, cityid)
+    airvalue              = "{:.1f}".format(airvalue) if isinstance(airvalue, float) else airvalue
+    watervalue, watertime = currentwatertemperature('0316a21383ff') # config? mainwatertemp?
+    watervalue            = "{:.1f}".format(watervalue) if isinstance(watervalue, float) else watervalue
+
+    return render_template(
+        'seepark_web.html',
+        apikey=apikey,
+        watervalue=watervalue,
+        watertime=watertime,
+        airvalue=airvalue,
+        airtime=airtime,
+    )
index 9113003..e3711ff 100644 (file)
 #openweathermap-widget-15 {
     width: 300px;
 }
+
+#current, #currentair, #currentwater {
+    margin: 0 auto;
+    text-align: center;
+    padding: 1em;
+    max-width: 20em;
+}
+
+#currentair {
+    background-color: lightblue;
+}
+
+#currentwater {
+    background-color: lightgreen;
+}
index 6997f7a..aabd1df 100644 (file)
        </head>
        <body>
                <h1>Daten zum Seepark Obsteig</h1>
+               <h2>Aktuelle Werte</h2>
+               <div id="current">
+               <p id="currentair">
+                       <strong>Luft: {{ airvalue }}°C</strong><br />
+                       <small>({{ airtime }})</small>
+               </p>
+               <p id="currentwater">
+                       <strong>Wasser: {{ watervalue }}°C</strong><br />
+                       <small>({{ watertime }})</small>
+               </p>
+               </div>
+
+               <h2>Der See</h2>
                <div id="chart1"></div>
                <div id="chart7"></div>
                <div id="chart31"></div>