#import requests as requests
#import json as json
#import datetime
import time
#import sys
#import network
from machine import Pin
from lcd import LCD
#from mail_alert import AlertMail
from stepper_motor import GORILLACELL_STEPMOTOR
from servo_motor import ServoMotor
# Lists to store pending and monitoring medicines
pendingMedicine = {}
monitoringMedicine = {}
button_enable = False
button_clicked = False
lcd = LCD()
stepper = GORILLACELL_STEPMOTOR()
servo_motor = ServoMotor()
#alert_mail = AlertMail()
medi_sw = Pin(0, Pin.IN)
# Function to create dummy data instead of fetching from server
def fetch_dummy_data():
# Simulated medicine data to mimic server response
data = {
"1": {"medicineStatus": "pending", "medicineTime": "22:37"},
"2": {"medicineStatus": "pending", "medicineTime": "22:39"},
"3": {"medicineStatus": "pending", "medicineTime": "22:41"}
}
print("Using dummy data:", data)
return data
# def fetch_data_from_server():
# try:
# response = requests.get("http://localhost:3000/espGet")
# if response.status_code == 200:
# data = json.loads(response.text)
# print("received data from server = ", data)
# return data
# else:
# print("Error fetching data, status code:", response.status_code)
# return {}
# except Exception as e:
# print("Error:", e)
# return {}
# Process and add pending medicines to the list
def process_medicines(medicines):
global pendingMedicine
for medi in list(medicines.keys()):
if medicines[medi]["medicineStatus"] == "pending":
pendingMedicine[medi] = medicines[medi]["medicineTime"]
print("Pending medicine:", pendingMedicine)
# Alarm function to sound the alert
def start_alarm(medicine):
lcd.dispStr(f"Take medicine {medicine}")
#clears screen when moving to next medicine
def clear_display():
lcd.clear()
def open_door():
global button_clicked
if button_enable:
servo_motor.set_servo_angle(180)
button_clicked = True
def mag_sensor(medi):
# add a loop to check if medi cap is taken
close_door()
def close_door():
servo_motor.set_servo_angle(90)
# Check pending medicines for dispensing
def check_pending_medicines():
global pendingMedicine, monitoringMedicine
for medi in list(pendingMedicine.keys()):
# Simulate dispensing logic
stepper.rotate(int(medi) * 45, 'cw')
start_alarm(medi)
monitoringMedicine[medi] = pendingMedicine[medi]
pendingMedicine.pop(medi)
break # Process only the first medicine at a time
# # check if it's time for any pending medicine
# def check_pending_medicines():
# global pendingMedicine, monitoringMedicine
# current_time = datetime.datetime.now().strftime("%H:%M")
# for medi in list(pendingMedicine.keys()):
# medicine_time = pendingMedicine[medi]
# print("current time ", current_time, " equals medicine time ", medicine_time)
# if current_time == medicine_time:
# stepper.rotate(int(medi) * 45, 'cw')
# start_alarm(medi)
# monitoringMedicine[medi] = pendingMedicine[medi]
# print("Monitoring medicine = ", monitoringMedicine)
# Function to monitor taken or missed medicines
# def monitor_medicines():
# global monitoringMedicine
# current_time_min = int(datetime.datetime.now().strftime("%M"))
# for medi in list(monitoringMedicine.keys()): # {"1":"22:37"}
# medi_minutes = int(monitoringMedicine[medi].split(":")[1])
# time_diff = (current_time_min - medi_minutes) # Time difference in minutes
# if time_diff < 0:
# time_diff += 60
# global button_enable
# button_enable = True
# if button_clicked: # Button pressed
# mag_sensor(medi)
# send_status_to_server(medi, "taken")
# monitoringMedicine.pop(medi)
# pendingMedicine.pop(medi)
# button_clicked = False
# elif time_diff >= 10: # Medicine missed after 10 minutes
# notify_missed_medicine(medi)
# send_status_to_server(medi, "missed")
# monitoringMedicine.pop(medi)
# pendingMedicine.pop(medi)
# print("time difference: ", time_diff)
# Function to send medicine status back to the server
# def send_status_to_server(medicine, status):
# try:
# data = {
# medicine: status
# }
# response = requests.post("http://localhost:3000/espPost", json=data)
# if response.status_code == 200:
# print("Status sent successfully:", status)
# else:
# print("Failed to send status:", response.status_code)
# except Exception as e:
# print("Error:", e)
# Notify user about missed medicine (add custom notification logic here)
# def notify_missed_medicine(medicine):
# alert_mail.send_alert(medicine)
# Main loop
# def main_loop():
# while True:
# medicines = fetch_data_from_server() #{"1":{"medicineStatus":"pending","medicineTime":"22:37"}}
# process_medicines(medicines)
# # checking if the medicine is already been added to monitoring list
# for (key, value) in medicines.items():
# if key not in monitoringMedicine:
# check_pending_medicines()
# elif monitoringMedicine[key] != value:
# check_pending_medicines()
# monitor_medicines()
# time.sleep(20) # Run every 20 seconds
# simulate taken or missed medicines
def monitor_medicines():
global monitoringMedicine, button_enable, button_clicked
elapsed_time = 0
for medi in list(monitoringMedicine.keys()):
print(f"Time to take medicine {medi}. Waiting for button press...")
button_enable = True
while elapsed_time < 100:
user_input = input("Press button? (yes/no): ")
if user_input.lower() == "yes":
open_door()
time.sleep(5) # Wait for 10 seconds after opening the lid
close_door()
clear_display() # Clear the display after taking medicine
print("Medicine taken.")
send_status_to_server(medi, "taken")
monitoringMedicine.pop(medi)
button_clicked = False
stepper.rotate(45, 'cw') # Rotate to the next position after closing the lid
return
elif user_input.lower() == "no":
print("Button not pressed. Waiting...")
time.sleep(5)
elapsed_time += 5
print(f"Medicine {medi} missed.")
notify_missed_medicine(medi)
send_status_to_server(medi, "missed")
clear_display() # Clear the display after missing the medicine
monitoringMedicine.pop(medi)
stepper.rotate(45, 'cw') # Rotate to the next position even if missed
# simulate Sending medicine status back to server.
def send_status_to_server(medicine, status):
print(f"Sending Medicine {medicine} status '{status}' to server.")
# Main loop
def main_loop():
medicines = fetch_dummy_data()
process_medicines(medicines)
while pendingMedicine or monitoringMedicine:
if pendingMedicine:
check_pending_medicines()
if monitoringMedicine:
monitor_medicines()
time.sleep(1)
main_loop()