SaturJyoon commited on
Commit
184c12a
·
verified ·
1 Parent(s): 100345f

Added app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py CHANGED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import queue
4
+ import threading
5
+ import pandas as pd
6
+ import joblib
7
+ from datetime import datetime
8
+ from flask import Flask
9
+ import paho.mqtt.client as mqtt
10
+
11
+ # ================= Configuration =================
12
+ # Use environment variables for flexibility, or keep your defaults
13
+ MQTT_BROKER = "broker.hivemq.com"
14
+ TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor"
15
+ TOPIC_PRED = "sic7/stage4/DI-Binary/prediction"
16
+ MQTT_PORT = 1883
17
+
18
+ # Load your pre-trained model (Ensure this filename matches your upload)
19
+ MODEL_PATH = "model.joblib"
20
+ model = joblib.load(MODEL_PATH)
21
+
22
+ # ================= Web Server (Health Check) =================
23
+ # Hugging Face needs this to stay "Green"
24
+ server = Flask(__name__)
25
+
26
+ @server.route('/')
27
+ def home():
28
+ return f"Random Forest MQTT Server is running. Last sync: {datetime.now()}"
29
+
30
+ def run_flask():
31
+ # Hugging Face uses port 7860 by default
32
+ server.run(host='0.0.0.0', port=7860)
33
+
34
+ # ================= MQTT Logic =================
35
+ message_queue = queue.Queue()
36
+
37
+ def on_connect(client, userdata, flags, rc):
38
+ print(f"Connected to Broker with result code {rc}")
39
+ client.subscribe(TOPIC_SENSOR)
40
+
41
+ def on_message(client, userdata, msg):
42
+ try:
43
+ data = json.loads(msg.payload.decode())
44
+ message_queue.put(data)
45
+ except Exception as e:
46
+ print(f"Error parsing message: {e}")
47
+
48
+ def process_loop(mqtt_client):
49
+ print("Inference loop started...")
50
+ while True:
51
+ # This blocks until a message is available
52
+ latest_msg = message_queue.get()
53
+
54
+ try:
55
+ # Extract data
56
+ temp = float(latest_msg["temp"])
57
+ hum = float(latest_msg["hum"])
58
+ soil = float(latest_msg["soil"])
59
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
60
+
61
+ # ML Prediction (Matching your DataFrame structure)
62
+ X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}])
63
+ X = X[["temp", "hum", "soil"]] # Ensure column order
64
+ pred = int(model.predict(X)[0]) # Convert to int for JSON/String serializing
65
+
66
+ # Log to console
67
+ print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Pred={pred}")
68
+
69
+ # Publish back to MQTT
70
+ mqtt_client.publish(TOPIC_PRED, f"CLASS:{pred}")
71
+
72
+ except Exception as e:
73
+ print(f"Error during prediction: {e}")
74
+
75
+ # Signal queue task completion
76
+ message_queue.task_done()
77
+
78
+ # ================= Main Execution =================
79
+ if __name__ == "__main__":
80
+ # 1. Setup MQTT Client
81
+ client = mqtt.Client()
82
+ client.on_connect = on_connect
83
+ client.on_message = on_message
84
+
85
+ client.connect(MQTT_BROKER, MQTT_PORT, 60)
86
+
87
+ # 2. Start Flask in a background thread
88
+ threading.Thread(target=run_flask, daemon=True).start()
89
+
90
+ # 3. Start the ML Processor in a background thread
91
+ threading.Thread(target=process_loop, args=(client,), daemon=True).start()
92
+
93
+ # 4. Start the MQTT Loop (Main Thread)
94
+ print("SERVER STARTED!")
95
+ client.loop_forever()