import ufp
import time
from utils import ExtrusionStepper, find_devices

MOTOR_IDS = (1, 2, 3, 4, 5) # plain, black, red
MOTORS : dict[int, ExtrusionStepper] = {}

def main():
    devices = find_devices().items()
    for mid, (port, client) in devices: 
        if mid in MOTOR_IDS:
            # reuse the connection find_devices already opened
            MOTORS[mid] = ExtrusionStepper(port, 0.5, client=client, speed=200, accel=400)
        else:
            client.close()
            
    print(MOTORS)
    try:
        while True:
            cmd = None
            while not cmd:
                cmd = input("Motor id, rotations: ")
            
            request_id, rots = (int(x) for x in cmd.split(','))
            print(f"Turning motor {request_id} by {rots} turns...")
            MOTORS[request_id]._turn_n(rots)
            print("Done")
    except KeyboardInterrupt:
        print("\nExiting")
    finally:
        for id, motor in MOTORS.items():
            motor.close()

if __name__ == "__main__":
    main()