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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from collections import deque
|
| 3 |
import gradio as gr
|
| 4 |
+
import paho.mqtt.client as mqtt
|
| 5 |
+
import json
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import plotly.express as px
|
| 9 |
|
| 10 |
+
# Data buffer to store received sensor data (max 100 records)
|
| 11 |
+
data_buffer = deque(maxlen=100)
|
| 12 |
|
| 13 |
+
# MQTT client and configuration variables (using your temperature sensor credentials)
|
| 14 |
+
client = mqtt.Client()
|
| 15 |
+
MQTT_BROKER = "b6bdb89571144b3d8e5ca4bbe666ddb5.s1.eu.hivemq.cloud"
|
| 16 |
+
MQTT_PORT = 8883
|
| 17 |
+
MQTT_TOPIC = "sensors/bme680/data"
|
| 18 |
+
MQTT_USERNAME = "LuthiraMQ"
|
| 19 |
+
MQTT_PASSWORD = "jLVx8y9v83gmgERTr0AP"
|
| 20 |
+
|
| 21 |
+
# Global variables to track connection and data status
|
| 22 |
+
connection_status = "❌ Not connected"
|
| 23 |
+
data_status = "⌛ Waiting for data..."
|
| 24 |
+
|
| 25 |
+
# Mutex for thread-safe status updates
|
| 26 |
+
status_lock = threading.Lock()
|
| 27 |
+
|
| 28 |
+
def get_status():
|
| 29 |
+
"""
|
| 30 |
+
Returns the current status of the MQTT connection and data reception.
|
| 31 |
+
"""
|
| 32 |
+
with status_lock:
|
| 33 |
+
return f"**MQTT Connection:** {connection_status}\n**Data Status:** {data_status}"
|
| 34 |
+
|
| 35 |
+
def update_data_status(new_status):
|
| 36 |
+
"""
|
| 37 |
+
Safely updates the data reception status.
|
| 38 |
+
"""
|
| 39 |
+
global data_status
|
| 40 |
+
with status_lock:
|
| 41 |
+
data_status = new_status
|
| 42 |
+
|
| 43 |
+
def on_connect(client, userdata, flags, rc):
|
| 44 |
+
"""
|
| 45 |
+
Callback for MQTT connection events.
|
| 46 |
+
"""
|
| 47 |
+
global connection_status
|
| 48 |
+
if rc == 0:
|
| 49 |
+
client.subscribe(MQTT_TOPIC)
|
| 50 |
+
connection_status = "✅ Connected"
|
| 51 |
+
else:
|
| 52 |
+
connection_status = f"❌ Connection failed (code {rc})"
|
| 53 |
+
|
| 54 |
+
def on_message(client, userdata, msg):
|
| 55 |
+
"""
|
| 56 |
+
Callback for processing incoming MQTT messages.
|
| 57 |
+
Expects JSON payload with keys: "temperature", "humidity", "pressure", "gas".
|
| 58 |
+
"""
|
| 59 |
+
try:
|
| 60 |
+
payload = json.loads(msg.payload.decode())
|
| 61 |
+
# Convert sensor values to float
|
| 62 |
+
temperature = float(payload.get("temperature", 0))
|
| 63 |
+
humidity = float(payload.get("humidity", 0))
|
| 64 |
+
pressure = float(payload.get("pressure", 0))
|
| 65 |
+
gas = float(payload.get("gas", 0))
|
| 66 |
+
# Use current time as timestamp
|
| 67 |
+
dt = datetime.now()
|
| 68 |
+
data_buffer.append({
|
| 69 |
+
'timestamp': dt,
|
| 70 |
+
'temperature': temperature,
|
| 71 |
+
'humidity': humidity,
|
| 72 |
+
'pressure': pressure,
|
| 73 |
+
'gas': gas
|
| 74 |
+
})
|
| 75 |
+
update_data_status("✅ Receiving data")
|
| 76 |
+
reset_inactivity_timer()
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Error processing message: {e}")
|
| 79 |
+
|
| 80 |
+
def connect_mqtt(broker, username, password):
|
| 81 |
+
"""
|
| 82 |
+
Connects to the MQTT broker using provided credentials.
|
| 83 |
+
"""
|
| 84 |
+
global MQTT_BROKER, MQTT_USERNAME, MQTT_PASSWORD, connection_status
|
| 85 |
+
try:
|
| 86 |
+
MQTT_BROKER = broker
|
| 87 |
+
MQTT_USERNAME = username
|
| 88 |
+
MQTT_PASSWORD = password
|
| 89 |
+
|
| 90 |
+
client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
|
| 91 |
+
# Configure TLS if not already set
|
| 92 |
+
if not client._ssl:
|
| 93 |
+
client.tls_set()
|
| 94 |
+
|
| 95 |
+
client.on_connect = on_connect
|
| 96 |
+
client.on_message = on_message
|
| 97 |
+
client.connect(MQTT_BROKER, MQTT_PORT, 60)
|
| 98 |
+
client.loop_start()
|
| 99 |
+
return "Connection initiated..."
|
| 100 |
+
except Exception as e:
|
| 101 |
+
connection_status = f"❌ Connection error: {str(e)}"
|
| 102 |
+
return f"Connection error: {str(e)}"
|
| 103 |
+
|
| 104 |
+
# Inactivity timer to detect when data stops arriving
|
| 105 |
+
inactivity_timer = None
|
| 106 |
+
|
| 107 |
+
def reset_inactivity_timer():
|
| 108 |
+
"""
|
| 109 |
+
Resets the inactivity timer to monitor data reception.
|
| 110 |
+
"""
|
| 111 |
+
global inactivity_timer
|
| 112 |
+
if inactivity_timer is not None:
|
| 113 |
+
inactivity_timer.cancel()
|
| 114 |
+
inactivity_timer = threading.Timer(5.0, on_inactivity)
|
| 115 |
+
inactivity_timer.start()
|
| 116 |
+
|
| 117 |
+
def on_inactivity():
|
| 118 |
+
"""
|
| 119 |
+
Callback for when no data is received within the timeout period.
|
| 120 |
+
"""
|
| 121 |
+
update_data_status("⌛ Waiting for data...")
|
| 122 |
+
|
| 123 |
+
def update_graph():
|
| 124 |
+
"""
|
| 125 |
+
Returns a Plotly figure showing Temperature over time from the data buffer.
|
| 126 |
+
"""
|
| 127 |
+
if not data_buffer:
|
| 128 |
+
fig = px.line(title="Waiting for Data...")
|
| 129 |
+
else:
|
| 130 |
+
df = pd.DataFrame(list(data_buffer))
|
| 131 |
+
fig = px.line(df, x='timestamp', y='temperature', title="Temperature Over Time")
|
| 132 |
+
fig.update_layout(
|
| 133 |
+
xaxis=dict(
|
| 134 |
+
type="date",
|
| 135 |
+
tickformat="%H:%M:%S",
|
| 136 |
+
title="Time"
|
| 137 |
+
),
|
| 138 |
+
yaxis=dict(title="Temperature (°C)")
|
| 139 |
+
)
|
| 140 |
+
return fig
|
| 141 |
+
|
| 142 |
+
def update_humidity_graph():
|
| 143 |
+
"""
|
| 144 |
+
Returns a Plotly figure showing Humidity over time from the data buffer.
|
| 145 |
+
"""
|
| 146 |
+
if not data_buffer:
|
| 147 |
+
fig = px.line(title="Waiting for Data...")
|
| 148 |
+
else:
|
| 149 |
+
df = pd.DataFrame(list(data_buffer))
|
| 150 |
+
fig = px.line(df, x='timestamp', y='humidity', title="Humidity Over Time")
|
| 151 |
+
fig.update_layout(
|
| 152 |
+
xaxis=dict(
|
| 153 |
+
type="date",
|
| 154 |
+
tickformat="%H:%M:%S",
|
| 155 |
+
title="Time"
|
| 156 |
+
),
|
| 157 |
+
yaxis=dict(title="Humidity (%)")
|
| 158 |
+
)
|
| 159 |
+
return fig
|
| 160 |
+
|
| 161 |
+
def update_metrics():
|
| 162 |
+
"""
|
| 163 |
+
Returns a Markdown string with the latest sensor readings.
|
| 164 |
+
"""
|
| 165 |
+
if not data_buffer:
|
| 166 |
+
return "No sensor data available yet."
|
| 167 |
+
df = pd.DataFrame(list(data_buffer))
|
| 168 |
+
latest = df.iloc[-1]
|
| 169 |
+
return (
|
| 170 |
+
f"**Latest Sensor Readings:** \n"
|
| 171 |
+
f"- Temperature: {latest['temperature']:.2f} °C \n"
|
| 172 |
+
f"- Humidity: {latest['humidity']:.2f} % \n"
|
| 173 |
+
f"- Pressure: {latest['pressure']:.2f} hPa \n"
|
| 174 |
+
f"- Gas: {latest['gas']:.2f} ohms \n\n"
|
| 175 |
+
f"{get_status()}"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Build the Gradio Blocks UI
|
| 179 |
+
with gr.Blocks() as app:
|
| 180 |
+
gr.Markdown("# Temperature Sensor Monitor")
|
| 181 |
+
gr.Markdown("## Connect to MQTT")
|
| 182 |
+
|
| 183 |
+
with gr.Row():
|
| 184 |
+
broker_input = gr.Textbox(
|
| 185 |
+
label="MQTT Broker",
|
| 186 |
+
value="b6bdb89571144b3d8e5ca4bbe666ddb5.s1.eu.hivemq.cloud"
|
| 187 |
+
)
|
| 188 |
+
username_input = gr.Textbox(
|
| 189 |
+
label="MQTT Username",
|
| 190 |
+
value="LuthiraMQ"
|
| 191 |
+
)
|
| 192 |
+
password_input = gr.Textbox(
|
| 193 |
+
label="MQTT Password",
|
| 194 |
+
value="jLVx8y9v83gmgERTr0AP",
|
| 195 |
+
type="password"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
connect_button = gr.Button("Connect")
|
| 199 |
+
connection_status_md = gr.Markdown(get_status, every=10)
|
| 200 |
+
|
| 201 |
+
gr.Markdown("### Temperature Graph")
|
| 202 |
+
temp_plot = gr.Plot(update_graph, every=2.5)
|
| 203 |
+
|
| 204 |
+
gr.Markdown("### Humidity Graph")
|
| 205 |
+
humidity_plot = gr.Plot(update_humidity_graph, every=2.5)
|
| 206 |
+
|
| 207 |
+
gr.Markdown("### Latest Sensor Readings")
|
| 208 |
+
sensor_metrics_md = gr.Markdown(update_metrics, every=2.5)
|
| 209 |
+
|
| 210 |
+
connect_button.click(
|
| 211 |
+
fn=connect_mqtt,
|
| 212 |
+
inputs=[broker_input, username_input, password_input],
|
| 213 |
+
outputs=[connection_status_md]
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
app.launch()
|