Spaces:
Sleeping
Sleeping
Commit ·
725a9ba
1
Parent(s): 2ef3756
updated mqtt to ws
Browse filesFiles changed (3)
- gradio/README.md+1-13
- gradio/app.py+21-14
- gradio/requirements.txtDeleted-16
12345678910111213## Gradio Apptitle: Machine Monitoringemoji: 🏭colorTo: bluesdk: gradiosdk_version: 4.44.1app_file: app.pypinned: true1## Gradio App
19 unmodified lines202122232425262728293031323334352 unmodified lines3839404142434445464748495051525354555657585960616263642 unmodified lines6768697071727374757677787980818219 unmodified linesINFLUXDB_BUCKET = "machine_monitoring"influx_client = InfluxDBClient3(host=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG,database="machine_monitoring")# MQTT setupMQTT_BROKER = "mqtt://broker.hivemq.com:1883"MQTT_TOPIC = "test_fan/current"def query_influxdb_gr():query = '''SELECT *FROM "fan"WHERE time >= now() - interval '3 week''''try:table = influx_client.query(query=query, language="sql")2 unmodified linesexcept:KeyError("Error with InfluxDB Integration")# Callback when a message is received from the serverdef on_message(client, userdata, message):global data_pointstry:payload = message.payload.decode()value = float(payload) # Assume the payload is a single float valuedata_points.append({"timestamp": time.time(), "current": value, "datetime": datetime.now().strftime('%H:%M:%S')})# Keep only the last MAX_DATA_POINTSif len(data_points) > MAX_DATA_POINTS:data_points.pop(0) # Remove the oldest data pointexcept ValueError:print(f"Received invalid payload: {payload}")# Set up MQTT clientclient = mqtt.Client(client_id="gradio_client", protocol=mqtt.MQTTv311)client.on_message = on_messageclient.connect(MQTT_BROKER, 1883, 60)client.subscribe(MQTT_TOPIC)# Start MQTT loop in a separate threadmqtt_thread = threading.Thread(target=client.loop_start)2 unmodified lines# Gradio componentsdef update_mqtt_live_data():# Convert timestamps to formatted time stringsdf = pd.DataFrame(data_points)return dfwith gr.Blocks() as app:gr.Markdown("# MQTT Data Visualization")gr.Markdown(f"Listening to MQTT topic: {MQTT_TOPIC}")line_plot = gr.LinePlot(update_mqtt_live_data, label="MQTT", x="datetime", y="current", every=1)gr.Markdown("# InfluxDB Data Visualization")line_plot = gr.LinePlot(query_influxdb_gr, label="InfluxDB", x="time", y="current", every=300)# Launch the appapp.launch()19 unmodified lines2021222324252627282930313233342 unmodified lines373839404142434445464748495051525354555657585960616263646566672 unmodified lines707172737475767778798081828384858687888919 unmodified linesINFLUXDB_BUCKET = "machine_monitoring"influx_client = InfluxDBClient3(host=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG,database="machine_monitoring")# MQTT setupMQTT_BROKER = "broker.hivemq.com"MQTT_TOPIC = "test_fan/current"def query_influxdb_gr():query = '''SELECT *FROM "fan"WHERE time >= now() - interval '3 weeks''''try:table = influx_client.query(query=query, language="sql")2 unmodified linesexcept:KeyError("Error with InfluxDB Integration")def on_connect(client, userdata, flags, reason_code, properties=None):print(f"Connected with result code {reason_code}")# Subscribing in on_connect() means that if we lose the connection and# reconnect then subscriptions will be renewed.client.subscribe(MQTT_TOPIC)def on_message(client, userdata, message):global data_pointstry:payload = message.payload.decode()value = float(payload) # Assume the payload is a single float valuedata_points.append({"timestamp": time.time(), "current": value, "datetime": datetime.now().strftime('%H:%M:%S')})# Keep only the last MAX_DATA_POINTSif len(data_points) > MAX_DATA_POINTS:data_points.pop(0) # Remove the oldest data pointexcept ValueError:print(f"Received invalid payload: {payload}")# Set up MQTT clientclient = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,protocol=mqtt.MQTTv5,transport='websockets')client.on_message = on_messageclient.on_connect = on_connectclient.ws_set_options(path="/mqtt", headers=None)client.connect(MQTT_BROKER, 8000, 60)# Start MQTT loop in a separate threadmqtt_thread = threading.Thread(target=client.loop_start)2 unmodified lines# Gradio componentsdef update_mqtt_live_data():# Convert timestamps to formatted time stringsif data_points:df = pd.DataFrame(data_points)return dfelse:df = pd.DataFrame([{"timestamp": time.time(), "current": 0, "datetime": datetime.now().strftime('%H:%M:%S')}])return dfwith gr.Blocks() as app:gr.Markdown("# MQTT Data Visualization")gr.Markdown(f"Listening to MQTT topic: {MQTT_TOPIC}")line_plot = gr.LinePlot(update_mqtt_live_data, label="MQTT", x="datetime", y="current", every=1)gr.Markdown("# InfluxDB Data Visualization")line_plot = gr.LinePlot(query_influxdb_gr, label="InfluxDB", x="time", y="current", every=300)gr.Markdown("# Plotly Version")# Launch the appapp.launch(share=True)
12345678910111213141516# matplotlib==3.7.0# paho-mqtt==2.1.0# pyOpenSSL==24.2.1# python-dotenv==1.0.1# gradio==4.44.1# gradio_client==1.3.0# huggingface-hub==0.25.2# Jinja2==3.1.4# numpy==2.0.2# pandas==2.2.3# plotly==5.24.1# requests==2.32.3# scipy==1.13.1# urllib3==2.2.3# influxdb-client==1.46.0# influxdb3-python==0.9.0gradio/README.md+1-13
gradio/app.py+21-14
gradio/requirements.txtDeleted-16