Use openweathermap module in web app.
[chrisu/seepark.git] / web / seepark_web.py
index 9ad59f124d3a78f18b81f49bf43f17885cd958ef..c0fd440d4da1e5f770c954fdb2d7c6ecc4295c29 100644 (file)
@@ -3,9 +3,14 @@ import datetime
 import time
 import configparser
 import os
+import sys
 from flask import Flask, render_template, jsonify, request
 import flask.json
 from sqlalchemy import create_engine
+import requests
+
+sys.path.append('..')
+from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
 
 
 class JSONEncoder(flask.json.JSONEncoder):
@@ -24,6 +29,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 +100,23 @@ def select_sensordata(initial_where, initial_sql_args):
     return result
 
 
+def currentairtemperature(apikey, cityid):
+    """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
+    try:
+        weatherdata = openweathermap_json(apikey, cityid)
+        return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
+    except OpenWeatherMapError:
+        return None, None
+
+
+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 +187,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,
+    )