def manual_move_end_setter():
    import RPi.GPIO as GPIO
    from time import sleep
    from DBFunctions import curtain_length, current_position, set_curtain_length

    while True:
        cnx = DBFunctions.start_connection()
        if not cnx: continue
        cursor = cnx.cursor(buffered=True)

        if GPIO.input(
                ENABLE_PIN
        ):  # motor is currently activated; wait before next check
            sleep(INTERVAL_BETWEEN_MANUAL_MOVEMENT_CHECKS)

        length = curtain_length(cursor)
        position = current_position(cursor)
        # if curtain open and position not marked at open end
        if GPIO.input(OPEN_STOP_PIN) and length != position:
            set_curtain_length(cnx, cursor, length)
        # if curtain closed and position not marked at closed end
        elif GPIO.input(CLOSED_STOP_PIN) and position:
            set_curtain_length(cnx, cursor, 0)

        sleep(INTERVAL_BETWEEN_MANUAL_MOVEMENT_CHECKS)

        cnx.close()
def calibrate(cnx, cursor):
    try:
        import RPi.GPIO as GPIO
        from DBFunctions import direction, set_curtain_length

        GPIOUtility.enable_motor()
        closed_direction = direction(cursor)
        move_to_closed(closed_direction)
        step_count = count_steps_from_closed_to_open()
        set_curtain_length(cnx, cursor, step_count)  # write count to DB
        GPIOUtility.disable_motor()
    except Exception as error:
        try:
            GPIOUtility.disable_motor()
        except:
            pass
        ErrorWriter.write_error(error)
def setup(cnx, cursor):
    import RPi.GPIO as GPIO
    from DBFunctions import set_direction_switch, set_curtain_length

    if GPIO.input(OPEN_STOP_PIN) or GPIO.input(CLOSED_STOP_PIN):
        raise Exception("To determine direction, curtain cannot be at an end")

    GPIOUtility.enable_motor()
    # move to end and orient
    first_stop_pin = move_to_an_end()
    # True (pin) & going "negative" (CLOSED_STOP_PIN) is `direction` = False
    # True (pin) & going "positive" (OPEN_STOP_PIN) is `direction` = True
    closed_direction = False if first_stop_pin == CLOSED_STOP_PIN else True
    set_direction_switch(cnx, cursor,
                         closed_direction)  # write direction to DB

    # get number of steps
    if OPEN_STOP_PIN == first_stop_pin: opposite_pin = CLOSED_STOP_PIN
    else: opposite_pin = OPEN_STOP_PIN
    step_count = count_steps_to_end(opposite_pin)
    set_curtain_length(cnx, cursor, step_count)  # write count to DB
    GPIOUtility.disable_motor()