+def select_sensordata(initial_where, initial_sql_args):
+ engine = open_engine(config)
+ with engine.connect() as conn:
+ where = [initial_where]
+ sql_args = [initial_sql_args]
+ begin = None
+ end = None
+ if 'begin' in request.args:
+ where.append('timestamp>=%s')
+ begin = request.args.get('begin', None, parse_datetime)
+ sql_args.append(begin)
+ if 'end' in request.args:
+ where.append('timestamp<=%s')
+ end = request.args.get('end', None, parse_datetime)
+ sql_args.append(end)
+ sql = 'select * from sensors where {} order by id'.format(' and '.join(where))
+ cursor = conn.execute(sql, *sql_args)
+ result = [dict(row) for row in cursor]
+
+ mode = request.args.get('mode', 'full')
+ if mode == 'consolidated':
+ if begin is None or end is None:
+ pass
+ 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
+
+ format = request.args.get('format', 'default')
+ if format == 'c3':
+ c3result = dict()
+ for row in result:
+ if not row['sensor_id'] in c3result:
+ c3result[row['sensor_id']] = list()
+ c3result[row['sensor_id']].append(row['value'])
+ if not row['sensor_id'] + '_x' in c3result:
+ c3result[row['sensor_id'] + '_x'] = list()
+ dt = row['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
+ c3result[row['sensor_id'] + '_x'].append(dt)
+ result = c3result
+ 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')
+
+