]> ToastFreeware Gitweb - chrisu/seepark.git/blobdiff - web/seepark_web.py
Ignore warning about duplicate key when inserting openweathermap data.
[chrisu/seepark.git] / web / seepark_web.py
index fc28fdead7f895951f9fd03ccf72ddbf573d83b4..e8b9da11dc6f0b4b20ca6c44841cc22825acb213 100644 (file)
@@ -61,57 +61,78 @@ class Sensors(db.Model):
     __tablename__ = 'sensors'
 
 
-def select_sensordata(initial_where):
-    query = Sensors.query.filter(initial_where)
-    begin = request.args.get('begin', None, parse_datetime)
-    end = request.args.get('end', None, parse_datetime)
+def select_sensordata(sensor_id, sensor_type, begin, end, mode):
+    query = Sensors.query
+    if sensor_id is not None:
+        query = query.filter(Sensors.sensor_id == sensor_id)
+    if sensor_type is not None:
+        query = query.filter(Sensors.value_type == sensor_type)
     if begin is not None:
         query = query.filter(Sensors.timestamp >= begin)
     if end is not None:
         query = query.filter(Sensors.timestamp <= end)
-    result = query.all()
-
-    mode = request.args.get('mode', 'full')
-    if mode == 'consolidated':
-        if begin is None or end is None:
-            pass
+    if mode == 'consolidated' and begin is None and end is None:
+        # copied from munin/master/_bin/munin-cgi-graph.in
+        # interval in seconds for data points
+        resolutions = dict(
+            day   =   300,
+            week  =  1800,
+            month =  7200,
+            year  = 86400,
+        )
+        duration = (end - begin).total_seconds()
+        day = 60 * 60 * 24
+        if duration < day:
+            resolution = resolutions['day']
+        elif duration < 7 * day:
+            resolution = resolutions['week']
+        elif duration < 31 * day:
+            resolution = resolutions['month']
         else:
-            # copied from munin/master/_bin/munin-cgi-graph.in
-            resolutions = dict(
-                day   =   300,
-                week  =  1800,
-                month =  7200,
-                year  = 86400,
-            )
-            duration = (end - begin).total_seconds()
-            day = 60 * 60 * 24
-            if duration < day:
-                resolution = resolutions['day']
-            elif duration < 7 * day:
-                resolution = resolutions['week']
-            elif duration < 31 * day:
-                resolution = resolutions['month']
-            else:
-                resolution = resolutions['year']
-            # TODO: filter out samples from 'result'
-            # like loop over results and skip if timestamp(n+1)-timestamp(n)<resolution
-
+            resolution = resolutions['year']
+        # TODO: filter out samples from 'result'
+        # something like 
+        # select mean(temperature) from sensors where ... group by mod(timestamp, resolution)
+        # func.avg(...)
+        #
+        # from https://stackoverflow.com/questions/4342370/grouping-into-interval-of-5-minutes-within-a-time-range
+        # SELECT
+        #    timestamp,  -- not sure about that
+        #        name,
+        #            count(b.name)
+        #            FROM time a, id 
+        #            WHERE …
+        #            GROUP BY 
+        #            UNIX_TIMESTAMP(timestamp) DIV 300, name
+    return query.all()
+
+
+def convert_to_c3(result):
+    c3result = defaultdict(list)
+    for row in result:
+        c3result[row.sensor_id].append(row.value)
+        dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
+        c3result[row.sensor_id + '_x'].append(dt)
+    return c3result
+
+
+def sensordata(sensor_id=None, sensor_type=None):
+    begin = request.args.get('begin', None, parse_datetime)
+    end = request.args.get('end', None, parse_datetime)
+    mode = request.args.get('mode', 'full')
     format = request.args.get('format', 'default')
+
+    result = select_sensordata(sensor_id, sensor_type, begin, end, mode)
+
     if format == 'c3':
-        c3result = defaultdict(list)
-        for row in result:
-            c3result[row.sensor_id].append(row.value)
-            dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
-            c3result[row.sensor_id + '_x'].append(dt)
-        return c3result
-    else:
-        return result
+        return convert_to_c3(result)
+    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)
+        url, weatherdata = openweathermap_json(apikey, cityid)
         return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
     except OpenWeatherMapError:
         return None, None
@@ -139,7 +160,7 @@ def sensorid(version, sensor_id):
     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
     """
-    result = select_sensordata(Sensors.sensor_id == sensor_id)
+    result = sensordata(sensor_id=sensor_id)
     return jsonify(result)
 
 
@@ -153,7 +174,7 @@ def sensortype(version, sensor_type):
     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
     """
-    result = select_sensordata(Sensors.value_type == sensor_type)
+    result = sensordata(sensor_type=sensor_type)
     return jsonify(result)