- engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
- return engine
-
-
-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]
+ return 'mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db)
+
+
+config = configparser.ConfigParser()
+config.read(os.environ['SEEPARKINI'])
+apikey = config.get('openweathermap', 'apikey')
+cityid = config.get('openweathermap', 'cityid')
+mainsensor = config.get('webapp', 'mainsensor')
+
+app = Flask(__name__)
+app.json_encoder = JSONEncoder
+app.config['SQLALCHEMY_DATABASE_URI'] = get_sqlalchemy_database_uri(config)
+app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
+db = SQLAlchemy(app)
+db.reflect(app=app)
+
+
+class Sensors(db.Model):
+ __tablename__ = 'sensors'
+
+
+class OpenWeatherMap(db.Model):
+ __tablename__ = 'openweathermap'
+
+
+def calc_grouping_resolution(begin, end):
+ """How many data points should be between the timestamps begin and end?"""
+ # copied from munin/master/_bin/munin-cgi-graph.in
+ # except day: 300 -> 600
+ resolutions = dict(
+ day = 600,
+ 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']
+ return resolution
+
+
+def select_sensordata(sensor_id, sensor_type, begin, end):
+ 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)
+ return query.all()
+
+
+def sensordata_to_xy(sensordata):
+ sensordata = list(sensordata)
+ x = np.array([d.timestamp for d in sensordata])
+ y = np.array([d.value for d in sensordata])
+ return x, y
+
+
+def select_sensordata_grouped(sensor_id, sensor_type, begin, end):
+ # determine resolution (interval in seconds for data points)
+ resolution = calc_grouping_resolution(begin, end)
+
+ # Let the database do the grouping. Example in SQL (MySQL):
+ # select to_seconds(datetime) DIV (60*60*24) as interval_id, min(datetime), max(datetime), min(temp), avg(temp), max(temp), count(temp) from openweathermap group by interval_id order by interval_id;
+ query = db.session.query(func.to_seconds(Sensors.timestamp).op('div')(resolution).label('g'),
+ func.from_unixtime(func.avg(func.unix_timestamp(Sensors.timestamp))).label('timestamp'),
+ func.avg(Sensors.value).label('value'),
+ Sensors.sensor_id, Sensors.value_type, Sensors.sensor_name)
+ 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)
+ query = query.filter(Sensors.timestamp >= begin)
+ query = query.filter(Sensors.timestamp <= end)
+ query = query.group_by('g', Sensors.sensor_id, Sensors.value_type, Sensors.sensor_name)
+ return query.all()
+
+
+def select_openweatherdata(cityid, begin, end):
+ query = OpenWeatherMap.query.filter(OpenWeatherMap.cityid == cityid)
+ if begin is not None:
+ query = query.filter(OpenWeatherMap.datetime >= begin)
+ if end is not None:
+ query = query.filter(OpenWeatherMap.datetime <= end)
+ return query.all()
+
+
+def openweatherdata_to_xy(openweatherdata):
+ openweatherdata = list(openweatherdata)
+ x = np.array([d.datetime for d in openweatherdata])
+ y = np.array([d.temp for d in openweatherdata])
+ return x, y
+
+
+def select_openweatherdata_grouped(cityid, begin, end):
+ # determine resolution (interval in seconds for data points)
+ resolution = calc_grouping_resolution(begin, end)
+
+ # Let the database do the grouping. Example in SQL (MySQL):
+ # select to_seconds(datetime) DIV (60*60*24) as interval_id, min(datetime), max(datetime), min(temp), avg(temp), max(temp), count(temp) from openweathermap group by interval_id order by interval_id;
+ query = db.session.query(func.to_seconds(OpenWeatherMap.datetime).op('div')(resolution).label('g'),
+ func.from_unixtime(func.avg(func.unix_timestamp(OpenWeatherMap.datetime))).label('datetime'),
+ func.avg(OpenWeatherMap.temp).label('temp'),
+ OpenWeatherMap.cityid)
+ OpenWeatherMap.query.filter(OpenWeatherMap.cityid == cityid)
+ query = query.filter(OpenWeatherMap.datetime >= begin)
+ query = query.filter(OpenWeatherMap.datetime <= end)
+ query = query.group_by('g', OpenWeatherMap.cityid)
+ return query.all()
+
+
+def estimate_swimmer_count(date):
+ return date.day
+
+
+def select_swimmerdata(begin, end):
+ def report_times(begin, end):
+ d = begin
+ while d < end:
+ for t in [10, 15]:
+ a = datetime.datetime.combine(d.date(), datetime.time(t))
+ if a >= d:
+ yield a
+ d += datetime.timedelta(days=1)
+ SwimmerData = collections.namedtuple('SwimmerData', ['datetime', 'count'])
+ for d in report_times(begin, end):
+ count = estimate_swimmer_count(d)
+ yield SwimmerData(d, count)
+