all repos — iot-project @ 2768cd3b1c1fba57c4b8cb879e28b2e0bb075796

backend_iot/views.py (view raw)

 1from backend_iot import app
 2from backend_iot.db import getLatestRecord, addRecord, get_aqi
 3from flask import request, redirect, render_template, abort
 4from datetime import datetime
 5
 6current_latitude, current_longitude = 45.46437891252755, 7.872049153560152
 7
 8def update_record(record):
 9    record["latitude"] = current_latitude
10    record["longitude"] = current_longitude
11    record["timestamp"] = datetime.now()
12    record["aqi"] = get_aqi(current_latitude, current_longitude)
13
14def latest_or_abort():
15    latest = getLatestRecord()
16    if latest is None:
17        return abort(400)
18    return latest
19
20@app.route("/")
21def index_route():
22    if request.method == 'GET':
23        return render_template("index.html")
24    
25    form = request.form
26    update_record(form)
27    addRecord(**form)
28
29editable_fields = ["t_target", "power", "fan_speed", "auto", "airflow"]
30
31@app.route("/data", methods = ['GET', 'POST'])
32def data_route():
33
34    if request.method == "GET":
35        return latest_or_abort()
36    
37    latest = getLatestRecord()
38    form = request.form
39
40    for key in form.keys():
41        if key not in latest.keys():
42            continue
43        if key == "fan_speed" and latest["auto"]:
44            continue
45        latest[key] = form[key]
46
47    update_record(latest)
48    addRecord(**latest)