- engine = open_engine(config)
- with engine.connect() as conn:
- cursor = conn.execute('select distinct sensor_id, sensor_name, value_type from sensors')
- result = [dict(row) for row in cursor]
- return jsonify(result)
-
-
-@app.route('/data/', defaults={'timespan': 1})
-@app.route("/data/<int:timespan>", methods=['GET'])
-def data(timespan):
- granularity = 5 * timespan # (every) minute(s) per day
- samples = 60/granularity * 24 * timespan # per hour over whole timespan
- s4m = []
- s4m_x = []
- s5m = []
- s5m_x = []
- end = time.time()
- start = end - samples * granularity * 60
-
- for i in range(int(samples)):
- s4m.append(uniform(-10,30))
- s5m.append(uniform(-10,30))
- s4mt = uniform(start, end)
- s5mt = uniform(start, end)
- s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
- s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
-
- data = {
- '0316a2193bff': s4m,
- '0316a2193bff_x': s4m_x,
- '0316a21383ff': s5m,
- '0316a21383ff_x': s5m_x,
- }
-
- return jsonify(data)
+ result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
+ return jsonify(result)
+
+
+@app.route('/api/<version>/sensor/id/<sensor_id>')
+def sensorid(version, sensor_id):
+ """Return all data for a specific sensor
+
+ URL parameters:
+ begin=<datetime>, optional, format like "2018-05-19T21:07:53"
+ end=<datetime>, optional, format like "2018-05-19T21:07:53"
+ 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 = sensordata(sensor_id=sensor_id)
+ return jsonify(result)
+
+
+@app.route('/api/<version>/sensor/type/<sensor_type>')
+def sensortype(version, sensor_type):
+ """Return all data for a specific sensor type
+
+ URL parameters:
+ begin=<datetime>, optional, format like "2018-05-19T21:07:53"
+ end=<datetime>, optional, format like "2018-05-19T21:07:53"
+ 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 = sensordata(sensor_type=sensor_type)
+ return jsonify(result)
+
+
+@app.route('/api/<version>/openweathermap/cities')
+def openweathermap_cities(version):
+ """List all city IDs found in the database"""
+ result = db.session.query(OpenWeatherMap.cityid).distinct().all()
+ return jsonify(result)
+
+
+@app.route('/api/<version>/openweathermap/city/<cityid>')
+def openweathermap_city(version, cityid):
+ """List all data found for a city"""
+ result = openweathermapdata(cityid=cityid)
+ return jsonify(result)
+
+
+@app.route('/api/<version>/currentairtemperature')
+def currentair(version):
+ value, timestamp = currentairtemperature(cityid)
+ return jsonify({"value": value, "timestamp": timestamp})
+
+
+@app.route('/api/<version>/currentwatertemperature')
+def currentwater(version):
+ value, timestamp = currentwatertemperature(mainsensor)
+ return jsonify({"value": value, "timestamp": timestamp})
+
+
+@app.route('/report/<int:year>-<int:month>')
+def report(year, month):
+
+ begin = datetime.datetime(year, month, 1)
+ end = add_month(begin)
+ data = list(select_sensordata(mainsensor, 'Wassertemperatur', begin, end))
+ x = np.array([d.timestamp for d in data])
+ y = np.array([d.value for d in data])
+
+ days_datetime = []
+ d = begin
+ while d < end:
+ days_datetime.append(d)
+ d = d + datetime.timedelta(1)
+
+ binary_pdf = io.BytesIO()
+ with PdfPages(binary_pdf) as pdf:
+ a4 = (29.7/2.54, 21./2.54)
+ title = 'Seepark Wassertemperatur {} {}'.format(MONTH_DE[begin.month-1], begin.year)
+ report_times = [datetime.time(10), datetime.time(15)]
+
+ # graphic
+ plt.figure(figsize=a4)
+ plt.plot(x, y)
+ plt.xticks(days_datetime, [''] * len(days_datetime))
+ plt.ylabel('Temperatur in °C')
+ plt.axis(xmin=begin, xmax=end)
+ plt.grid()
+ plt.title(title)
+
+ # table
+ columns = []
+ for d in days_datetime:
+ columns.append('{}.'.format(d.day))
+ rows = []
+ for t in report_times:
+ rows.append('Wasser {:02d}:{:02d} °C'.format(t.hour, t.minute))
+ cells = []
+ for t in report_times:
+ columns.append('{}.'.format(d.day))
+ row_cells = []
+ for d in days_datetime:
+ report_datetime = datetime.datetime.combine(d.date(), t)
+ closest_index = np.argmin(np.abs(x - report_datetime))
+ if abs(x[closest_index] - report_datetime) > datetime.timedelta(hours=1):
+ cell = 'N/A'
+ else:
+ value = y[closest_index]
+ cell = '{:.1f}'.format(value)
+ row_cells.append(cell)
+ cells.append(row_cells)
+ table = plt.table(cellText=cells, colLabels=columns, rowLabels=rows, loc='bottom')
+ table.scale(xscale=1, yscale=2)
+ plt.title(title)
+ plt.subplots_adjust(left=0.15, right=0.97, bottom=0.3) # do not cut row labels
+ pdf.savefig()
+
+ pdf_info = pdf.infodict()
+ pdf_info['Title'] = title
+ pdf_info['Author'] = 'Chrisu Jähnl'
+ pdf_info['Subject'] = 'Wassertemperatur'
+ pdf_info['Keywords'] = 'Seepark Wassertemperatur'
+ pdf_info['CreationDate'] = datetime.datetime.now()
+ pdf_info['ModDate'] = datetime.datetime.today()
+
+ response = make_response(binary_pdf.getvalue())
+ response.headers['Content-Type'] = 'application/pdf'
+ response.headers['Content-Disposition'] = 'attachment; filename=seepark_{:04d}-{:02d}.pdf'.format(year, month)
+ return response