Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
2
Indexable
Never
"""Creates a MQTT aware web site"""
from signal import signal, SIGINT
from sys import exit
import json
import sqlite3
from flask import Flask, render_template
from flask_mqtt import Mqtt
import measurements_db as db


app = Flask(__name__)
app.config["MQTT_BROKER_URL"] = "myggen.mooo.com"
app.config["MQTT_BROKER_PORT"] = 8883

mqtt = Mqtt(app)


@app.route("/", methods=["GET", "POST"])
@app.route("/index", methods=["GET", "POST"])
def post_lastest_measurement():
    """Routing to the frontpage of the website"""
    latest_measurement = create_latest_measurement()
    return render_template("index.html", latest_measurements=latest_measurement)

def create_latest_measurement():
    """"Creating measurement post"""
    with sqlite3.connect("measurements.db") as conn:
        c_obj = conn.cursor()
        c_obj.execute("SELECT * FROM measurements ORDER BY date DESC LIMIT 1")
        return c_obj.fetchall()

@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    print("connected to MQTT broker...", end="")
    mqtt.subscribe("Echo/#")
    print("subscribed")


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    topic = message.topic
    payload = message.payload.decode()
    if topic.endswith("/json"):
        payload = json.loads(payload)
        if "temperature" in payload:
            db.store_measurement(payload["latest_TVOC"], payload["latest_eCO2"], payload["max_TVOC"], payload["min_TVOC"], payload["max_eCO2"], payload["min_eCO2"])
    print(f"Received MQTT on {topic}: {payload}")


# inspired by https://www.devdungeon.com/content/python-catch-sigint-ctrl-c
def handler(signal_received, frame):
    # Handle any cleanup here
    print("SIGINT or CTRL-C detected. Exiting gracefully")
    mqtt.unsubscribe_all()
    exit(0)


if __name__ == "__main__":
    signal(SIGINT, handler)
    app.run(
        use_reloader=False,
    )