import utime as time
import uasyncio as asyncio
from machine import Pin, RTC
import rp2
import sys

import dht11
import math

from alt_temp import Temp
from machine import Pin
time.sleep(0.5)


LED = Pin(25, Pin.OUT)
LED.on()
relay1 = Pin(28, Pin.OUT, Pin.PULL_DOWN)
relay2 = Pin(27, Pin.OUT, Pin.PULL_DOWN)
relay3 = Pin(16, Pin.OUT, Pin.PULL_DOWN)

sensor = Pin(14, Pin.IN)

# Assuming the async Temp() function is already defined as mentioned earlier

# Async function to control small fan
async def small_fan(current_temp):
    print('small fan control')
    if current_temp is not None:
        print(f"Current temperature for small fan: {current_temp}")
        if current_temp > 65:
            print("Temperature > 65°F, turning on relay1 (small fan)")
            relay1.on()  # Turn relay1 on
            await asyncio.sleep(60)
        else:
            print("Temperature <= 65°F, turning off relay1 (small fan)")
            relay1.off()  # Turn relay1 off
            await asyncio.sleep(60)
    else:
        print("Failed to read temperature, skipping small fan control for now.")


# Async function to control filter fan
async def filter_fan(current_temp):
    print('filter fan control')
    if current_temp is not None:
        print(f"Current temperature for filter fan: {current_temp}")
        if current_temp > 75:
            print("Temperature > 75°F, turning on relay2 (filter fan)")
            relay2.on()  # Turn relay2 on
            await asyncio.sleep(180)
            relay2.off()  # Turn relay2 off after 3 minutes
            await asyncio.sleep(180)
        else:
            print("Temperature <= 75°F, ensuring relay2 (filter fan) is off")
            relay2.off()  # Ensure relay2 is off
            await asyncio.sleep(60)
    else:
        print("Failed to read temperature, skipping filter fan control for now.")


# Async function to control dryer
async def dryer():
    print('dryer control')
    
    # Dryer relay is controlled by a sensor, no temperature input needed here
    if sensor.value():  # If the sensor is triggered (e.g., something to dry is detected)
        print("Sensor triggered, turning on relay3 (dryer)")
        relay3.on()  # Turn relay3 on
        await asyncio.sleep(20)  # Run dryer for 20 seconds
#         print('dryer done')
        relay3.off()  # Turn off the dryer relay
#         print('dryer off')
        await asyncio.sleep(600)  # Wait 10 minutes before next cycle
#         print ("done sleeping dryer")
    else:
        print("Sensor not triggered, ensuring relay3 (dryer) is off")
        relay3.off()  # Ensure relay3 is off


# Main function that runs all tasks concurrently
async def main():
    while True:
        current_temp = await Temp()  # Get temperature once per cycle
        if current_temp is not None:
            print(f"Main loop: Current temperature is {current_temp}°F")
        else:
            print("Main loop: Failed to read temperature.")
        
        # Run small_fan and filter_fan with the same temperature value
        await asyncio.gather(
            small_fan(current_temp),
            filter_fan(current_temp),
            dryer()  # Dryer doesn't need temperature
        )

        # Add delay between temperature checks (e.g., 60 seconds)
        await asyncio.sleep(60)


# Run the event loop
try:
    print('starting event loop')
    asyncio.run(main())
except Exception as e:
    print(f"Exception in event loop: {e}")
finally:
    asyncio.new_event_loop()  # Ensure the event loop is reset after execution

