import uasyncio as asyncio
from machine import Pin
#from aiohttp import ClientSession, web
#import accelstepper
from accelstepper import AccelStepper
import display

# Set up the stepper motor
dirn = 19 #Stepper direction pin
step = 18 #Stepper step pin
en = 5 #stepper enable pin
STEPPER_PINS = [Pin(dirn, Pin.OUT), Pin(step, Pin.OUT)]
stepper = AccelStepper(interface = 1, *STEPPER_PINS)
AccelStepper.set_enable_pin(en)

# Set the maximum speed and acceleration
controller.setMaxSpeed(1000)
controller.setAcceleration(500)

motor_running = False # Flag to track whether the motor is running
RPM = 0 # Flag to track currently-set RPM

# Set up the physical buttons
slow_button = Pin(25, Pin.IN, Pin.PULL_UP)
medium_button = Pin(33, Pin.IN, Pin.PULL_UP)
fast_button = Pin(32, Pin.IN, Pin.PULL_UP)
encoder_button = Pin(13, Pin.IN, Pin.PULL_UP)
go_button = Pin(35, Pin.IN, Pin.PULL_UP)
stop_button = Pin(34, Pin.IN, Pin.PULL_UP)
#restart_button = Pin(..., Pin.IN, Pin.PULL_UP)  # Add a new button to restart the event loop

# Create an event to signal when the program should exit
exit_event = asyncio.Event()

# Define the interrupt handler functions
async def slow_handler(pin):
    global RPM, lastpressed
    RPM = slowRPM
    stepper.set_speed(100)
    speed = 100
    #display.text("Stepper Motor Speed: {} steps/sec".format(stepper.speed()), 0, 0)
    display.show()
    async with ClientSession() as session:
        async with session.post('http://localhost:8080/forward', json={'speed': 100}) as resp:
            print(await resp.text())
    # Reset the exit event to prevent the sleep task from being triggered
    exit_event.clear()

async def backward_handler(pin):
    stepper.move(-100)
    speed = -100
    display.text("Stepper Motor Speed: {} steps/sec".format(speed), 0, 0)
    display.show()
    async with ClientSession() as session:
        async with session.post('http://localhost:8080/backward', json={'speed': 100}) as resp:
            print(await resp.text())
    # Reset the exit event to prevent the sleep task from being triggered
    exit_event.clear()

async def stop_handler(pin):
    stepper.move(0)
    speed = 0
    display.text("Stepper Motor Stopped", 0, 0)
    display.show()
    async with ClientSession() as session:
        async with session.post('http://localhost:8080/stop') as resp:
            print(await resp.text())
    # Reset the exit event to prevent the sleep task from being triggered
    exit_event.clear()

async def restart_handler(pin):
    # Reset the exit event to restart the event loop
    exit_event.clear()

# Initialise the display
display.draw_screen()

# Attach the interrupt handler functions to the physical buttons
slow_button.irq(trigger=Pin.IRQ_FALLING, handler=slow_handler)
medium_button.irq(trigger=Pin.IRQ_FALLING, handler=medium_handler)
fast_button.irq(trigger=Pin.IRQ_FALLING, handler=fast_handler)
encoder_button.irq(trigger=Pin.IRQ_FALLING, handler=encoder_handler)
stop_button.irq(trigger=Pin.IRQ_FALLING, handler=stop_handler)
#restart_button.irq(trigger=Pin.IRQ_FALLING, handler=restart_handler)

# Start the event loop
# while not exit_event.is_set():
#     asyncio.sleep(1)

# Create a sleep task that waits for 10 minutes of inactivity before displaying a message and setting the exit event
async def sleep_task():
    await asyncio.sleep(600)  # Sleep for 10 minutes
    display.text("Controller Going to Sleep", 0, 16)
    display.show()
    exit_event.set()

# Start the sleep task
asyncio.create_task(sleep_task())

# Run the event loop indefinitely
while True:
    asyncio.run_until_complete(exit_event.wait())

A4988