-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
91 lines (69 loc) · 2.62 KB
/
Copy pathmain.py
File metadata and controls
91 lines (69 loc) · 2.62 KB
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
# main.py
# Continuous AI service for SmartFlood (DEMO MODE)
# Waits 10s → reads data → processes AI → waits 5s → saves → repeat
import time
from datetime import datetime, UTC
from db import sensor_readings_col, weather_readings_col, ai_predictions_col
from predictor import predict_flood_risk
print("🤖 SmartFlood AI Service started (DEMO MODE: 10s READ → 5s SAVE)...")
while True:
# 1️⃣ WAIT BEFORE READING
print("\n⏳ Waiting 5 seconds before reading data...")
time.sleep(5)
print("🔍 Reading latest data for all sensors...")
# 2️⃣ Get all sensor IDs
sensor_ids = sensor_readings_col.distinct("sensorId")
if not sensor_ids:
print("⚠️ No sensors found.")
continue
for sensor_id in sensor_ids:
print(f"\n📡 Processing sensor: {sensor_id}")
# Latest sensor reading
sensor = sensor_readings_col.find_one(
{"sensorId": sensor_id},
sort=[("createdAt", -1)]
)
# Latest weather reading
weather = weather_readings_col.find_one(
{"sensorId": sensor_id},
sort=[("createdAt", -1)]
)
if not sensor or not weather:
print(f"⚠️ Missing data for {sensor_id}. Skipping...")
continue
# 3️⃣ Extract features
water_level = sensor.get("waterLevel", 0)
rain_1h = weather.get("rainfall_1h", 0)
rain_3h = weather.get("rainfall_3h", 0)
created_at = sensor.get("createdAt", datetime.now(UTC))
hour = created_at.hour
day_of_week = created_at.weekday()
month = created_at.month
# 4️⃣ AI prediction
risk_level, risk_score = predict_flood_risk(
water_level, rain_1h, rain_3h
)
print(f"🧠 AI result for {sensor_id}: {risk_level.upper()}")
# 5️⃣ WAIT BEFORE SAVING
print("⏳ Waiting 5 seconds before saving...")
time.sleep(5)
# 6️⃣ Save to MongoDB
prediction = {
"sensorId": sensor_id,
"inputs": {
"waterLevel": water_level,
"rainfall_1h": rain_1h,
"rainfall_3h": rain_3h,
"hour": hour,
"dayOfWeek": day_of_week,
"month": month
},
"prediction": {
"riskLevel": risk_level,
"riskScore": risk_score
},
"createdAt": datetime.now(UTC)
}
ai_predictions_col.insert_one(prediction)
print(f"✅ Prediction saved for {sensor_id}")
print("\n🔁 Cycle complete (≈15 seconds total).")