-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_dashboard.py
More file actions
79 lines (64 loc) · 2.2 KB
/
Copy pathweb_dashboard.py
File metadata and controls
79 lines (64 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
import os, json, time, datetime
from flask import Flask, request, render_template, send_from_directory
from flask_cors import CORS
from pathlib import Path
from dotenv import load_dotenv
import paho.mqtt.client as mqtt
load_dotenv()
app = Flask(__name__)
CORS(app)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATE_DIR = os.path.join(BASE_DIR, "readings")
STATE_PATH = os.path.join(STATE_DIR, "readings.json")
MQTT_BROKER = os.getenv('MQTT_BROKER')
MQTT_PORT = 1883
MQTT_USER = os.getenv('MQTT_USER')
MQTT_PASSWORD = os.getenv('MQTT_PASSWORD')
USER_ID = os.getenv('USER_ID')
ENV_DATA = f"/{USER_ID}/telemetry/environment"
def load_readings():
try:
with open(STATE_PATH) as f:
data = json.load(f)
ts = data.get("ts")
if not ts:
return None
age = int(time.time()) - ts
time_str = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
data["age"] = age
data["time_str"] = time_str
return data
except FileNotFoundError:
return None
except Exception as e:
print("Error loading state:", e)
return None
@app.route('/images/<path:filename>')
def images(filename):
return send_from_directory(Path(app.root_path) / 'images', filename)
@app.route('/')
def index():
data = load_readings()
temperature = data.get("temperature")
humidity = data.get("humidity")
owTemp = data.get("owTemp")
owHumidity = data.get("owHumidity")
return render_template('dashboard.html', temperature=temperature, humidity=humidity, owTemp=owTemp, owHumidity=owHumidity)
def on_connect(client, userdata, flags, rc):
print("MQTT connected:", rc)
client.subscribe(ENV_DATA)
def on_message(client, userdata, msg):
data = json.loads(msg.payload.decode("utf-8"))
data["ts"] = int(time.time())
with open(STATE_PATH, "w") as f:
json.dump(data, f)
print("State updated:", data)
client = mqtt.Client()
client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_BROKER, MQTT_PORT, 60)
client.loop_start()
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)