File size: 3,036 Bytes
184c12a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec20a8
184c12a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import json
import queue
import threading
import pandas as pd
import joblib
from datetime import datetime
from flask import Flask
import paho.mqtt.client as mqtt

# ================= Configuration =================
# Use environment variables for flexibility, or keep your defaults
MQTT_BROKER = "broker.hivemq.com"
TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor"
TOPIC_PRED = "sic7/stage4/DI-Binary/prediction"
MQTT_PORT = 1883

# Load your pre-trained model (Ensure this filename matches your upload)
MODEL_PATH = "rf_model.pkl"
model = joblib.load(MODEL_PATH)

# ================= Web Server (Health Check) =================
# Hugging Face needs this to stay "Green"
server = Flask(__name__)

@server.route('/')
def home():
    return f"Random Forest MQTT Server is running. Last sync: {datetime.now()}"

def run_flask():
    # Hugging Face uses port 7860 by default
    server.run(host='0.0.0.0', port=7860)

# ================= MQTT Logic =================
message_queue = queue.Queue()

def on_connect(client, userdata, flags, rc):
    print(f"Connected to Broker with result code {rc}")
    client.subscribe(TOPIC_SENSOR)

def on_message(client, userdata, msg):
    try:
        data = json.loads(msg.payload.decode())
        message_queue.put(data)
    except Exception as e:
        print(f"Error parsing message: {e}")

def process_loop(mqtt_client):
    print("Inference loop started...")
    while True:
        # This blocks until a message is available
        latest_msg = message_queue.get()
        
        try:
            # Extract data
            temp = float(latest_msg["temp"])
            hum  = float(latest_msg["hum"])
            soil = float(latest_msg["soil"])
            ts   = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            # ML Prediction (Matching your DataFrame structure)
            X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}])
            X = X[["temp", "hum", "soil"]] # Ensure column order
            pred = int(model.predict(X)[0]) # Convert to int for JSON/String serializing

            # Log to console
            print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Pred={pred}")

            # Publish back to MQTT
            mqtt_client.publish(TOPIC_PRED, f"CLASS:{pred}")
            
        except Exception as e:
            print(f"Error during prediction: {e}")
        
        # Signal queue task completion
        message_queue.task_done()

# ================= Main Execution =================
if __name__ == "__main__":
    # 1. Setup MQTT Client
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    
    client.connect(MQTT_BROKER, MQTT_PORT, 60)

    # 2. Start Flask in a background thread
    threading.Thread(target=run_flask, daemon=True).start()

    # 3. Start the ML Processor in a background thread
    threading.Thread(target=process_loop, args=(client,), daemon=True).start()

    # 4. Start the MQTT Loop (Main Thread)
    print("SERVER STARTED!")
    client.loop_forever()