Spaces:
Sleeping
Sleeping
File size: 2,905 Bytes
239b861 4fc5fa3 deb26c4 4fc5fa3 deb26c4 239b861 4fc5fa3 239b861 4fc5fa3 239b861 09c5bc7 deb26c4 4fc5fa3 deb26c4 077de14 4fc5fa3 09c5bc7 4fc5fa3 deb26c4 4fc5fa3 deb26c4 4fc5fa3 09c5bc7 deb26c4 09c5bc7 4fc5fa3 deb26c4 239b861 4fc5fa3 239b861 4fc5fa3 239b861 | 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 96 | from flask import Flask
import threading
import json
import joblib
import numpy as np
import pandas as pd
from datetime import datetime
import paho.mqtt.client as mqtt
import queue
# ================= HF Health Check =================
server = Flask(__name__)
@server.route('/')
def health_check(): return "OK"
def run_flask():
# Must listen on 0.0.0.0 and port 7860
server.run(host='0.0.0.0', port=7860)
# ================= MQTT Configuration =================
MQTT_BROKER = "broker.hivemq.com"
TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor"
TOPIC_PRED = "sic7/stage4/DI-Binary/prediction"
MQTT_PORT = 1883
# Define the client globally so process_loop can use it
client = mqtt.Client()
model = joblib.load("rf_model.pkl")
print("Model loaded!")
logs = []
message_queue = queue.Queue()
# ================= MQTT Callbacks =================
def on_connect(client, userdata, flags, rc):
print("Connected →", rc)
client.subscribe(TOPIC_SENSOR)
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload.decode())
# FIX THE DELAY: Clear the queue so we only process the latest sensor reading
while not message_queue.empty():
try:
message_queue.get_nowait()
except queue.Empty:
break
message_queue.put(data)
except Exception as e:
print("Error parsing message:", e)
# ================= Processor Thread =================
def process_loop():
global logs
while True:
# This blocks until a message is available
latest_msg = message_queue.get()
if latest_msg:
try:
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
X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}])[["temp","hum","soil"]]
pred = model.predict(X)[0]
# Logging
logs.append([ts, temp, hum, soil, pred])
print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Prediction={pred}")
# Kirim balik ke ESP32
client.publish(TOPIC_PRED, f"CLASS:{int(pred)}")
except Exception as e:
print("Processing error:", e)
# ================= Main =================
if __name__ == "__main__":
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_BROKER, MQTT_PORT, 60)
# 1. Start web server (HF requirement)
threading.Thread(target=run_flask, daemon=True).start()
# 2. Start ML processing
threading.Thread(target=process_loop, daemon=True).start()
print("SERVER STARTED!")
# 3. Start MQTT loop in main thread
client.loop_forever() |