import time
import ufp
import sys
from utils import ExtrusionStepper, print_connected

PORT = "/dev/cu.usbmodem101"  # find yours with: ls /dev/cu*  (or pass it: python extrude.py /dev/cu.usbmodemXXXX)

def main():
    port = sys.argv[1] if len(sys.argv) > 1 else PORT
    stepper = ExtrusionStepper(port_name=port, start_current=0.5, speed=200)
    try:
        if "get_id" in stepper.m.functions:
            print_connected([stepper.m.get_id()])
        # stepper._turn_n(2)
        print("Starting interactive portion")
        last_cmd = None
        while True:
            cmd = input("Volume to deposit (cc, Enter repeats last): ").strip()
            if not cmd:
                if last_cmd is None:
                    continue
                cmd = last_cmd
            try:
                volume_cc = float(cmd)
            except ValueError:
                print(f"error: {cmd!r} is not a number")
                continue
            last_cmd = cmd
            print(f"Confirmed: depositing {volume_cc}cc of batter")
            turns = stepper.extrude_volume(volume_cc)
            print(f"Computed {turns:.2f} turns")
            while stepper.moving:
                time.sleep(0.1)
            print()
    except (KeyboardInterrupt, EOFError):
        print("\nExiting")
    finally:
        stepper.close()


if __name__ == "__main__":
    main()
