Update app.py
Browse files
app.py
CHANGED
|
@@ -1,336 +1,344 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from pydantic import BaseModel, validator
|
| 3 |
-
import requests
|
| 4 |
-
import uvicorn
|
| 5 |
-
import firebase_admin
|
| 6 |
-
from firebase_admin import credentials, firestore
|
| 7 |
-
import logging
|
| 8 |
-
from datetime import datetime
|
| 9 |
-
import pytz
|
| 10 |
-
import os
|
| 11 |
-
from fastapi import APIRouter, HTTPException
|
| 12 |
-
import requests
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# Set up logging
|
| 16 |
-
logging.basicConfig(level=logging.INFO)
|
| 17 |
-
logger = logging.getLogger(__name__)
|
| 18 |
-
|
| 19 |
-
app = FastAPI()
|
| 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 |
-
if isinstance(obj,
|
| 56 |
-
return
|
| 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 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
]
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
#
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel, validator
|
| 3 |
+
import requests
|
| 4 |
+
import uvicorn
|
| 5 |
+
import firebase_admin
|
| 6 |
+
from firebase_admin import credentials, firestore
|
| 7 |
+
import logging
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
import pytz
|
| 10 |
+
import os
|
| 11 |
+
from fastapi import APIRouter, HTTPException
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
router = APIRouter()
|
| 15 |
+
# Set up logging
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
app = FastAPI()
|
| 20 |
+
|
| 21 |
+
@app.get("/", include_in_schema=False)
|
| 22 |
+
async def _health_check():
|
| 23 |
+
return {"status": "healthy"}
|
| 24 |
+
|
| 25 |
+
app.include_router(router)
|
| 26 |
+
|
| 27 |
+
# Initialize Firebase Admin SDK
|
| 28 |
+
try:
|
| 29 |
+
cred = credentials.Certificate("serviceAccountKey.json")
|
| 30 |
+
firebase_admin.initialize_app(cred)
|
| 31 |
+
db = firestore.client()
|
| 32 |
+
except Exception as e:
|
| 33 |
+
logger.error(f"Failed to initialize Firebase Admin SDK: {str(e)}")
|
| 34 |
+
raise
|
| 35 |
+
class UpdateStatusRequest(BaseModel):
|
| 36 |
+
userId: str
|
| 37 |
+
medicineName: str
|
| 38 |
+
medicineTime: str # Expected format: "HH:MM"
|
| 39 |
+
|
| 40 |
+
class Credentials(BaseModel):
|
| 41 |
+
esp32_ip: str
|
| 42 |
+
user: str # Changed from email to user
|
| 43 |
+
|
| 44 |
+
@validator("esp32_ip")
|
| 45 |
+
def validate_esp32_ip(cls, value):
|
| 46 |
+
# Remove http:// or https:// if present
|
| 47 |
+
value = value.replace("http://", "").replace("https://", "")
|
| 48 |
+
# Check for invalid IP like 0.0.0.0
|
| 49 |
+
if "0.0.0.0" in value:
|
| 50 |
+
raise ValueError("Invalid ESP32 IP address: 0.0.0.0 is not a valid destination address")
|
| 51 |
+
return value
|
| 52 |
+
|
| 53 |
+
def convert_to_serializable(obj):
|
| 54 |
+
"""Convert Firestore timestamps and other non-serializable objects to JSON-serializable format."""
|
| 55 |
+
if isinstance(obj, firebase_admin.firestore.firestore.DocumentReference):
|
| 56 |
+
return str(obj.path)
|
| 57 |
+
if hasattr(obj, 'isoformat'): # Handles DatetimeWithNanoseconds
|
| 58 |
+
return obj.isoformat()
|
| 59 |
+
if isinstance(obj, dict):
|
| 60 |
+
return {k: convert_to_serializable(v) for k, v in obj.items()}
|
| 61 |
+
if isinstance(obj, list):
|
| 62 |
+
return [convert_to_serializable(item) for item in obj]
|
| 63 |
+
return obj
|
| 64 |
+
|
| 65 |
+
def convert_times_to_ist(medicine_times):
|
| 66 |
+
utc = pytz.utc
|
| 67 |
+
ist = pytz.timezone("Asia/Kolkata")
|
| 68 |
+
converted_times = []
|
| 69 |
+
|
| 70 |
+
for t in medicine_times:
|
| 71 |
+
try:
|
| 72 |
+
if isinstance(t, datetime):
|
| 73 |
+
utc_time = t.astimezone(utc)
|
| 74 |
+
elif isinstance(t, str):
|
| 75 |
+
if "Z" in t:
|
| 76 |
+
utc_time = datetime.fromisoformat(t.replace("Z", "+00:00")).astimezone(utc)
|
| 77 |
+
else:
|
| 78 |
+
utc_time = datetime.fromisoformat(t).astimezone(utc)
|
| 79 |
+
else:
|
| 80 |
+
logger.warning(f"[convert_times_to_ist] Unsupported type for medicineTime: {type(t)}")
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
ist_time = utc_time.astimezone(ist)
|
| 84 |
+
converted_times.append(ist_time.strftime("%H:%M")) # HH:MM format
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.warning(f"[convert_times_to_ist] Error converting time '{t}': {e}")
|
| 87 |
+
return converted_times
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@app.post("/send_medicineData")
|
| 91 |
+
async def send_medicineData(data: Credentials):
|
| 92 |
+
try:
|
| 93 |
+
logger.info(f"Received request: {data}")
|
| 94 |
+
|
| 95 |
+
# Step 1: Retrieve the medicines array from Firestore using user ID
|
| 96 |
+
logger.info(f"Fetching medicines data for user: {data.user}")
|
| 97 |
+
doc_ref = db.collection("users").document(data.user)
|
| 98 |
+
doc = doc_ref.get()
|
| 99 |
+
|
| 100 |
+
if not doc.exists:
|
| 101 |
+
logger.error("User data not found")
|
| 102 |
+
raise HTTPException(status_code=404, detail={"error": "User data not found"})
|
| 103 |
+
|
| 104 |
+
user_data = doc.to_dict()
|
| 105 |
+
medicines_data = user_data.get("medicines", []) # Fetch medicines list safely
|
| 106 |
+
|
| 107 |
+
if not medicines_data:
|
| 108 |
+
logger.error("Medicines data not found for this user")
|
| 109 |
+
raise HTTPException(status_code=404, detail={"error": "Medicines data not found for this user"})
|
| 110 |
+
|
| 111 |
+
# Step 2: Extract and filter medicine details based on endDate
|
| 112 |
+
current_date = datetime.now(pytz.UTC) # Current date in UTC
|
| 113 |
+
logger.info(f"Current date (UTC): {current_date}")
|
| 114 |
+
|
| 115 |
+
extracted_medicines = []
|
| 116 |
+
for medicine in medicines_data:
|
| 117 |
+
end_date_raw = medicine.get("endDate")
|
| 118 |
+
if not end_date_raw:
|
| 119 |
+
logger.warning(f"Medicine missing endDate: {medicine}")
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
# Handle endDate (already converted to datetime by Firestore Admin SDK)
|
| 124 |
+
if isinstance(end_date_raw, datetime):
|
| 125 |
+
end_date = end_date_raw
|
| 126 |
+
if end_date.tzinfo is None: # If no timezone info, assume UTC
|
| 127 |
+
end_date = end_date.replace(tzinfo=pytz.UTC)
|
| 128 |
+
else:
|
| 129 |
+
end_date = end_date.astimezone(pytz.UTC) # Convert to UTC for comparison
|
| 130 |
+
elif isinstance(end_date_raw, str):
|
| 131 |
+
# Fallback for string format (e.g., "April 17, 2025 at 12:00:00 AM UTC+5:30")
|
| 132 |
+
end_date_str = end_date_raw.replace("at ", "").replace("\u202f", " ")
|
| 133 |
+
end_date = datetime.strptime(end_date_str, "%B %d, %Y %I:%M:%S %p UTC%z")
|
| 134 |
+
end_date = end_date.astimezone(pytz.UTC) # Convert to UTC for comparison
|
| 135 |
+
else:
|
| 136 |
+
logger.warning(f"Unsupported endDate type: {type(end_date_raw)}, value: {end_date_raw}")
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
# Only include medicines with endDate in the future
|
| 140 |
+
if end_date > current_date:
|
| 141 |
+
extracted_medicines.append({
|
| 142 |
+
"doseFrequency": medicine.get("doseFrequency"),
|
| 143 |
+
"endDate": medicine.get("endDate"),
|
| 144 |
+
"medicineNames": medicine.get("medicineNames", []),
|
| 145 |
+
"medicineTimes": convert_times_to_ist(medicine.get("medicineTimes", {})),
|
| 146 |
+
"selectedDays": medicine.get("selectedDays", [])
|
| 147 |
+
})
|
| 148 |
+
|
| 149 |
+
else:
|
| 150 |
+
logger.info(f"Skipping medicine with expired endDate: {end_date_raw}")
|
| 151 |
+
|
| 152 |
+
except ValueError as e:
|
| 153 |
+
logger.warning(f"Failed to parse endDate: {end_date_raw}, error: {str(e)}")
|
| 154 |
+
continue
|
| 155 |
+
|
| 156 |
+
# Step 3: Check if there are any valid medicines to send
|
| 157 |
+
if not extracted_medicines:
|
| 158 |
+
logger.info("No medicines with endDate in the future found.")
|
| 159 |
+
return {
|
| 160 |
+
"message": "No medicines with endDate in the future found.",
|
| 161 |
+
"medicines": []
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
# Convert any non-serializable objects (e.g., timestamps)
|
| 165 |
+
extracted_medicines = convert_to_serializable(extracted_medicines)
|
| 166 |
+
|
| 167 |
+
# Step 4: Send the medicines data to ESP32
|
| 168 |
+
esp32_ip = data.esp32_ip.replace("http://", "").replace("https://", "")
|
| 169 |
+
esp32_url = f"http://{esp32_ip}/credentials"
|
| 170 |
+
logger.info(f"Sending medicines data to ESP32 at {esp32_url}")
|
| 171 |
+
esp32_response = requests.post(esp32_url, json={"medicines": extracted_medicines}, timeout=20)
|
| 172 |
+
esp32_response.raise_for_status()
|
| 173 |
+
|
| 174 |
+
logger.info("Medicines data sent successfully")
|
| 175 |
+
return {
|
| 176 |
+
"message": "Medicines data sent successfully",
|
| 177 |
+
"medicines": [
|
| 178 |
+
{
|
| 179 |
+
"medicineNames": med.get("medicineNames", []),
|
| 180 |
+
"medicineTimes": med.get("medicineTimes", [])
|
| 181 |
+
}
|
| 182 |
+
for med in extracted_medicines
|
| 183 |
+
],
|
| 184 |
+
"esp32_response": esp32_response.text
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
except requests.exceptions.RequestException as e:
|
| 188 |
+
logger.error(f"Request error: {str(e)}")
|
| 189 |
+
raise HTTPException(status_code=500, detail={"error": f"Failed to connect to ESP32: {str(e)}"})
|
| 190 |
+
except HTTPException as e:
|
| 191 |
+
raise e
|
| 192 |
+
except Exception as e:
|
| 193 |
+
logger.error(f"Unexpected error: {str(e)}", exc_info=True)
|
| 194 |
+
raise HTTPException(status_code=500, detail={"error": f"Unexpected error: {str(e)}"})
|
| 195 |
+
|
| 196 |
+
def send_command(data: Credentials, command: str):
|
| 197 |
+
try:
|
| 198 |
+
esp32_ip = data.esp32_ip.replace("http://", "").replace("https://", "")
|
| 199 |
+
url = f"http://{esp32_ip}/command/{command}"
|
| 200 |
+
logger.info(f"Sending command: {command} to {url}")
|
| 201 |
+
response = requests.get(url, timeout=10)
|
| 202 |
+
response.raise_for_status()
|
| 203 |
+
return {"message": f"{command.capitalize()} command sent successfully", "esp32_response": response.text}
|
| 204 |
+
except requests.exceptions.RequestException as e:
|
| 205 |
+
raise HTTPException(status_code=500, detail={"error": f"Failed to send {command} command: {str(e)}"})
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def ping_device(ip: str) -> bool:
|
| 210 |
+
try:
|
| 211 |
+
# Run the ping command and capture the output
|
| 212 |
+
response = os.popen(f'ping {ip}').read()
|
| 213 |
+
|
| 214 |
+
# Check if "Request timed out" or "Destination host unreachable" appears in the response
|
| 215 |
+
if "Request timed out" in response or "Destination host unreachable" in response:
|
| 216 |
+
return False
|
| 217 |
+
else:
|
| 218 |
+
return True
|
| 219 |
+
except Exception as e:
|
| 220 |
+
print(f"Error while pinging: {e}")
|
| 221 |
+
return False
|
| 222 |
+
|
| 223 |
+
# Endpoint to check the microcontroller's availability
|
| 224 |
+
@app.post("/command/microcontroller")
|
| 225 |
+
def check_microcontroller(data: Credentials):
|
| 226 |
+
# First, check if the ESP32 is reachable using the ping_device function
|
| 227 |
+
if not ping_device(data.esp32_ip):
|
| 228 |
+
return {"status": "error", "message": f"Microcontroller at {data.esp32_ip} is not reachable."}
|
| 229 |
+
|
| 230 |
+
# If reachable, return a success message without sending any command to the ESP32
|
| 231 |
+
return {"status": "success", "message": f"Microcontroller at {data.esp32_ip} is reachable."}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@app.post("/command/reset")
|
| 235 |
+
def reset_device(data: Credentials):
|
| 236 |
+
return send_command(data, "reset")
|
| 237 |
+
|
| 238 |
+
@app.post("/command/camera")
|
| 239 |
+
def check_camera(data: Credentials):
|
| 240 |
+
return send_command(data, "camera")
|
| 241 |
+
|
| 242 |
+
@app.post("/command/lcd")
|
| 243 |
+
def check_lcd(data: Credentials):
|
| 244 |
+
return send_command(data, "lcd")
|
| 245 |
+
|
| 246 |
+
@app.post("/command/motor")
|
| 247 |
+
def check_motor(data: Credentials):
|
| 248 |
+
return send_command(data, "motor")
|
| 249 |
+
|
| 250 |
+
@app.post("/command/battery")
|
| 251 |
+
def check_battery(data: Credentials):
|
| 252 |
+
return send_command(data, "battery")
|
| 253 |
+
|
| 254 |
+
@app.post("/update_medicine_status")
|
| 255 |
+
def update_medicine_status(req: UpdateStatusRequest):
|
| 256 |
+
try:
|
| 257 |
+
current_date = datetime.now().strftime('%d-%m-%Y')
|
| 258 |
+
print(f"[INFO] Processing for user={req.userId}, medicine={req.medicineName}, time={req.medicineTime}")
|
| 259 |
+
|
| 260 |
+
user_ref = db.collection("users").document(req.userId)
|
| 261 |
+
user_doc = user_ref.get()
|
| 262 |
+
|
| 263 |
+
if not user_doc.exists:
|
| 264 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 265 |
+
|
| 266 |
+
user_data = user_doc.to_dict()
|
| 267 |
+
medicines = user_data.get("medicines", [])
|
| 268 |
+
|
| 269 |
+
print(f"[DEBUG] Total medicine entries: {len(medicines)}")
|
| 270 |
+
|
| 271 |
+
# First, find all matches by name
|
| 272 |
+
matched_indices = [
|
| 273 |
+
idx for idx, med in enumerate(medicines)
|
| 274 |
+
if req.medicineName in med.get("medicineNames", [])
|
| 275 |
+
]
|
| 276 |
+
|
| 277 |
+
print(f"[DEBUG] Found {len(matched_indices)} medicine(s) with name match")
|
| 278 |
+
|
| 279 |
+
target_index = None
|
| 280 |
+
|
| 281 |
+
if len(matched_indices) == 1:
|
| 282 |
+
target_index = matched_indices[0]
|
| 283 |
+
else:
|
| 284 |
+
# Multiple matches, match by time
|
| 285 |
+
for idx in matched_indices:
|
| 286 |
+
for ts in medicines[idx].get("medicineTimes", []):
|
| 287 |
+
try:
|
| 288 |
+
if hasattr(ts, "strftime"):
|
| 289 |
+
time_str = ts.strftime("%H:%M")
|
| 290 |
+
print(f"[TRACE] Comparing time: {time_str} == {req.medicineTime}")
|
| 291 |
+
if time_str == req.medicineTime:
|
| 292 |
+
target_index = idx
|
| 293 |
+
break
|
| 294 |
+
except Exception as e:
|
| 295 |
+
print(f"[ERROR] Timestamp parsing failed: {e}")
|
| 296 |
+
if target_index is not None:
|
| 297 |
+
break
|
| 298 |
+
|
| 299 |
+
if target_index is None:
|
| 300 |
+
raise HTTPException(status_code=404, detail="Matching medicine name and time not found.")
|
| 301 |
+
|
| 302 |
+
# Update the status
|
| 303 |
+
print(f"[INFO] Updating index {target_index}")
|
| 304 |
+
if "status" not in medicines[target_index]:
|
| 305 |
+
medicines[target_index]["status"] = {}
|
| 306 |
+
medicines[target_index]["status"][current_date] = "taken"
|
| 307 |
+
|
| 308 |
+
# Push the full list back
|
| 309 |
+
user_ref.update({"medicines": medicines})
|
| 310 |
+
print(f"[SUCCESS] Updated medicine status at index {target_index}")
|
| 311 |
+
|
| 312 |
+
return {"message": f"Medicine status updated at index {target_index}"}
|
| 313 |
+
|
| 314 |
+
except Exception as e:
|
| 315 |
+
print(f"[ERROR] {e}")
|
| 316 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 317 |
+
|
| 318 |
+
class BuzzerRequest(BaseModel):
|
| 319 |
+
esp32_ip: str
|
| 320 |
+
sound_type: str # Options: relaxing, soft_melody, gentle_chime, calm_tune, beep_beep
|
| 321 |
+
|
| 322 |
+
@app.post("/buzzer/play")
|
| 323 |
+
def play_buzzer(data: BuzzerRequest):
|
| 324 |
+
valid_sounds = ["relaxing", "soft_melody", "gentle_chime", "calm_tune", "beep_beep"]
|
| 325 |
+
|
| 326 |
+
if data.sound_type not in valid_sounds:
|
| 327 |
+
raise HTTPException(status_code=400, detail="Invalid sound type selected.")
|
| 328 |
+
|
| 329 |
+
try:
|
| 330 |
+
url = f"http://{data.esp32_ip}/play_buzzer?sound={data.sound_type}"
|
| 331 |
+
response = requests.get(url, timeout=5)
|
| 332 |
+
response.raise_for_status()
|
| 333 |
+
return {
|
| 334 |
+
"status": "success",
|
| 335 |
+
"message": f"Playing {data.sound_type} on ESP32",
|
| 336 |
+
"esp32_response": response.text
|
| 337 |
+
}
|
| 338 |
+
except requests.RequestException as e:
|
| 339 |
+
raise HTTPException(status_code=500, detail=f"Failed to send buzzer command: {e}")
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
import os
|
| 343 |
+
port = int(os.environ.get("PORT", 5000))
|
| 344 |
+
uvicorn.run("app:app", host="0.0.0.0", port=port, reload=True)
|