evelyn-nesher19 commited on
Commit
bec53a0
·
verified ·
1 Parent(s): 8132001

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import paho.mqtt.client as mqtt
3
+ import json
4
+ import pandas as pd
5
+ from datetime import datetime
6
+ from collections import deque
7
+ import plotly.express as px
8
+ import time
9
+
10
+ # Storage for data points
11
+ data_buffer = deque(maxlen=100)
12
+
13
+ # MQTT client and configuration variables
14
+ client = mqtt.Client()
15
+ MQTT_BROKER = ""
16
+ MQTT_PORT = 8883
17
+ MQTT_TOPIC = "FX-120i/e6632c8593690c30"
18
+ MQTT_USERNAME = ""
19
+ MQTT_PASSWORD = ""
20
+
21
+ def on_connect(client, userdata, flags, rc):
22
+ if rc == 0:
23
+ print("Connected to MQTT broker")
24
+ client.subscribe(MQTT_TOPIC)
25
+ return "Connected to MQTT broker"
26
+ else:
27
+ return f"Connection failed with code {rc}"
28
+
29
+ def on_message(client, userdata, msg):
30
+ try:
31
+ payload = json.loads(msg.payload.decode())
32
+ weight = float(payload["Current Weight"].replace('g', '').strip().replace('+', ''))
33
+ timestamp = f"{payload['Date']} {payload['Time']}"
34
+ dt = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
35
+ data_buffer.append({'timestamp': dt, 'weight': weight})
36
+ except Exception as e:
37
+ print(f"Error: {e}")
38
+
39
+ def connect_mqtt(hivemq_host, username, password):
40
+ global MQTT_BROKER, MQTT_USERNAME, MQTT_PASSWORD
41
+ MQTT_BROKER = hivemq_host
42
+ MQTT_USERNAME = username
43
+ MQTT_PASSWORD = password
44
+
45
+ client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
46
+
47
+ # Check if SSL/TLS has already been configured before setting it
48
+ if not client._ssl:
49
+ client.tls_set()
50
+
51
+ client.on_connect = on_connect
52
+ client.on_message = on_message
53
+ client.connect(MQTT_BROKER, MQTT_PORT, 60)
54
+ client.loop_start()
55
+
56
+ def update_graph():
57
+ if not data_buffer:
58
+ fig = px.line(title="Waiting for Data...")
59
+ else:
60
+ df = pd.DataFrame(list(data_buffer))
61
+ fig = px.line(df, x='timestamp', y='weight', title="Weight Over Time")
62
+ fig.update_layout(
63
+ xaxis=dict(
64
+ type="date",
65
+ tickformat="%H:%M:%S",
66
+ title="Time"
67
+ ),
68
+ yaxis=dict(title="Weight (g)")
69
+ )
70
+ return fig
71
+
72
+ with gr.Blocks() as app:
73
+ gr.Markdown("# Weight Monitor")
74
+
75
+ # Connect to MQTT section
76
+ gr.Markdown("## Connect to MQTT")
77
+
78
+ # Input fields for HiveMQ connection
79
+ with gr.Row():
80
+ hivemq_host = gr.Textbox(
81
+ label="HiveMQ Host:",
82
+ value="f74268785e954de0970c4bd66f31b0a1.s1.eu.hivemq.cloud"
83
+ )
84
+ mqtt_username = gr.Textbox(
85
+ label="HiveMQ Username:",
86
+ value="evnesher"
87
+ )
88
+ mqtt_password = gr.Textbox(
89
+ label="HiveMQ Password:",
90
+ value="Gfx8360",
91
+ type="password"
92
+ )
93
+
94
+ # Connect button
95
+ connect_button = gr.Button("Connect")
96
+
97
+ # Graph display with auto-refresh
98
+ plot = gr.Plot(
99
+ update_graph,
100
+ every= 2.5 # Updates every 2.5 second
101
+ )
102
+
103
+ # Connect button action
104
+ connect_button.click(
105
+ fn=connect_mqtt,
106
+ inputs=[hivemq_host, mqtt_username, mqtt_password],
107
+ )
108
+
109
+ if __name__ == "__main__":
110
+ app.launch()