import pigpio
import sys
import tty
import termios
import select
import argparse
from random import randrange, shuffle
from time import sleep

# How much the angle of a servo is changed on an increment
ANGLE_STEP_DEGREES = 1

# Types of command for an individual servo
COMMAND_ANGLE_INCREMENT = 0   # Single parameter is the angle to increment by in degrees
COMMAND_ANGLE_CONVERGE = 1 # Two parameters: angle to converge on and the increment to do it by
COMMAND_ANGLE_SET = 2 # Two parameters: angle to set and sleep (in seconds) between increments to get there
COMMAND_JIGGLE = 3 # Single parameter is the angle to jiggle by

# The sleep between steps when doing an angle set command
SLEEP_ANGLE_SET_SECONDS = 0.1

# The change of angle to use to crack an egg
CRACK_EGG_ANGLE_DEGREES = 5

# Servo class
class Servo():
    '''Servo class'''
    def __init__(self, pi, gpio, name=None, limit_upper_degrees=None, limit_lower_degrees=None):
        '''Create a servo, needs a reference to the pigpiod class, the GPIO and a name for the servo'''
        self.pi = pi
        self.gpio = gpio
        self.name = name
        self.limit_upper_degrees = limit_upper_degrees
        self.limit_lower_degrees = limit_lower_degrees
        self.angle_at_limit = False
        self.angle_degrees = 0
    def __enter__(self):
        self.Start()
        return self
    def __exit__(self, type, value, traceback):
        del type
        del value
        del traceback
        self.Stop()
    def _convert_pulse_width_microseconds(self, angle_degrees):
        '''Private: return the pulse width corresponding to a given angle'''
        # We loop here so that we don't overshoot the angle due to rounding
        loop_count = 0
        angle_target_degrees = angle_degrees
        angle_at_limit = False
        while loop_count < 100:
            loop_count += 1
            _angle_degrees = angle_target_degrees
            angle_at_limit = False
            if self.limit_upper_degrees:
                _angle_degrees = min(_angle_degrees, self.limit_upper_degrees)
                if _angle_degrees == self.limit_upper_degrees:
                    angle_at_limit = True
            if self.limit_lower_degrees:
                _angle_degrees = max(_angle_degrees, self.limit_lower_degrees)
                if not angle_at_limit and _angle_degrees == self.limit_lower_degrees:
                    angle_at_limit = True
            pulse_width_microseconds = 1500 + (_angle_degrees / 90) * 1000
            pulse_width_microseconds = max(min(pulse_width_microseconds, 2500), 500)
            # Turn the pulse width back into an angle and check that rounding hasn't taken us over
            if abs(self._convert_angle_degrees(pulse_width_microseconds)) <= abs(_angle_degrees):
               # Done
               break;
            else:
               if angle_target_degrees > 0:
                   angle_target_degrees -= 1
               else:
                   angle_target_degrees += 1
        if loop_count >= 100:
            print(f"WARNING: unable to set angle {angle_degrees} degrees event after {loop_count} iterations.")
        return pulse_width_microseconds, angle_at_limit
    def _convert_angle_degrees(self, pulse_width_microseconds):
        '''Private: return the angle corresponding to a given pulse width'''
        return (pulse_width_microseconds - 1500) * 90 / 1000
    def _set_angle_degrees(self, angle_degrees, no_movement=False):
        '''Private: set the servo to the given angle, returning the angle set'''
        pulse_width_microseconds, angle_at_limit = self._convert_pulse_width_microseconds(angle_degrees)
        new_angle_degrees = self._convert_angle_degrees(pulse_width_microseconds)
        if not no_movement:
            self.angle_degrees = new_angle_degrees
            self.angle_at_limit = angle_at_limit
            self.pi.set_servo_pulsewidth(self.gpio, pulse_width_microseconds)
            if self.name:
                print(f"'{self.name}' servo, ", end='')
            print(f"GPIO {self.gpio:02d}: angle {self.angle_degrees:+3.0f} degrees, pulse {pulse_width_microseconds:4.0f} us", end='')
            if self.angle_at_limit:
                print(" AT LIMIT", end='')
            print("")
            sleep(0.05)
        return new_angle_degrees
    def Start(self):
        '''Set pin to be an output with no servo pulses'''
        self.pi.set_mode(self.gpio, pigpio.OUTPUT)
        self.pi.set_servo_pulsewidth(self.gpio, 0)
    def Stop(self):
        '''Stop the servo'''
        self.pi.set_servo_pulsewidth(self.gpio, 0)
    def GetName(self):
        '''Get the servo name'''
        return self.name
    def IncAngleDegrees(self, angle_degrees, no_movement=False):
        '''Increment the angle of a servo by a given amount (which may be negative), returning the new angle'''
        return self._set_angle_degrees(self.angle_degrees + angle_degrees, no_movement)
    def SetAngleDegrees(self, angle_degrees):
        '''Set a servo to a given angle, returning the angle set'''
        return self._set_angle_degrees(angle_degrees)
    def GetAngleDegrees(self):
        '''Get the servo angle'''
        return self.angle_degrees
    def GetAngleAtLimit(self):
        '''Get whether we've hit a limit or not'''
        return self.angle_at_limit

# Get keyboard input: for non-blocking input, specify a timeout value
def getch(timeout_seconds=None):
    fd = sys.stdin.fileno()
    saved_settings = termios.tcgetattr(fd)
    try:
        # Switch echo off
        new_settings = saved_settings[:]
        new_settings[3] &= ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSADRAIN, new_settings)
        # Set unbuffered
        tty.setraw(fd)
        x = None
        if timeout_seconds is None or select.select([sys.stdin], [], [], timeout_seconds)[0]:
            x = sys.stdin.read(1)
        # Check for arrow keys (start with 0x1b)
        if x == '\x1b':
            # Read two more characters
            sys.stdin.read(1)  # Discard the '['
            x = sys.stdin.read(1)
        # Raise SIGINT if CTRL-C (ASCII 0x03)
        elif x == '\x03':
            termios.tcsetattr(fd, termios.TCSADRAIN, saved_settings)
            raise KeyboardInterrupt
            # Won't get to this line
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, saved_settings)
    return x

# Return True if a number is non-negative
def non_negative(x):
    return abs(x) != x

# Do COMMAND_ANGLE_INCREMENT
def do_command_angle_increment(servo_dictionary, servo_key, angle_increment_degrees):
   servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees)

# Do COMMAND_ANGLE_SET
def do_command_angle_set(servo_dictionary, servo_key, angle_set_degrees, sleep_seconds=0):
    loop_count = 0
    angle_delta = servo_dictionary[servo_key].GetAngleDegrees() - angle_set_degrees
    angle_delta_sign_change = False
    while angle_delta != 0 and angle_delta_sign_change == False and loop_count < 100:
        loop_count += 1
        angle_increment_degrees = ANGLE_STEP_DEGREES
        if angle_delta > 0:
             angle_increment_degrees = -angle_increment_degrees
        # Test if the increment would go past the delta
        angle_delta_new = servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees, True) - angle_set_degrees
        angle_delta_sign_change = (non_negative(angle_delta_new) != non_negative(angle_delta))
        if not angle_delta_sign_change:
            # S'OK, do it
            angle_delta_new = servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees) - angle_set_degrees
            sleep(sleep_seconds)
        angle_delta = angle_delta_new
    if loop_count >= 100:
        print(f"WARNING: unable to set angle {angle_set_degrees} degrees even after {loop_count} iterations.")

# Do COMMAND_ANGLE_CONVERGE
def do_command_angle_converge(servo_dictionary, servo_key, angle_converge_degrees, angle_increment_degrees):
    angle_increment_degrees_abs = abs(angle_increment_degrees)
    if servo_dictionary[servo_key].GetAngleDegrees() > angle_converge_degrees:
        angle_increment_degrees_abs = -angle_increment_degrees_abs
    servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees_abs)

# Do COMMAND_JIGGLE
def do_command_jiggle(servo_dictionary, servo_key, angle_degrees):
    servo_dictionary[servo_key].IncAngleDegrees(angle_degrees)
    servo_dictionary[servo_key].IncAngleDegrees(-angle_degrees)
    servo_dictionary[servo_key].IncAngleDegrees(-angle_degrees)
    servo_dictionary[servo_key].IncAngleDegrees(angle_degrees)

# Perform a command on a servo
def do_command(servo_dictionary, servo_key, command_type, parameter_list):
    if command_type == COMMAND_ANGLE_INCREMENT:
        do_command_angle_increment(servo_dictionary, servo_key, parameter_list[0])
    elif command_type == COMMAND_ANGLE_SET:
        do_command_angle_set(servo_dictionary, servo_key, parameter_list[0], parameter_list[1])
    elif command_type == COMMAND_ANGLE_CONVERGE:
        do_command_angle_converge(servo_dictionary, servo_key, parameter_list[0], parameter_list[1])
    elif command_type == COMMAND_JIGGLE:
        do_command_jiggle(servo_dictionary, servo_key, parameter_list[0])

# Do random(ish) actions
def random_actions(allow_keyboard_input, servo_dictionary, motion_dictionary, egg_count=-1):
    print("Making things happen randomly, press another valid key to return to normal")
    # The lists: actions may appear multiple times to happen more frequently
    # Each of the lists in action_dictionary are operated in parallel.
    # Each action is performed count times before moving on to the next action
    # The first action list are the leaning ones, the second are the head rotations, the third are the eggs cracking
    # index tracks which action type is being performed
    action_dictionary = {'lean': {'type_list': ['forwards', 'backwards', 'left', 'right'], 'index': 0, 'count': 0, 'rand_range': 15, 'rand_min': 5, 'rand_max': 50},
                         'rotate': {'type_list': ['rotate_left', 'rotate_right', 'rotate_right'], 'index': 0, 'count': 0, 'rand_range': 5, 'rand_min': 15, 'rand_max': 30},
                         'crack': {'type_list': ['crack_0', 'crack_1', 'crack_2'], 'index': 0, 'count': 0}}
    if egg_count >= 0:
        # Make the egg count the number specified
        if egg_count == 0:
            del action_dictionary['crack']
            print(f"Cracking no egg(s)."); 
        else:
            original_list = action_dictionary['crack']['type_list']
            action_dictionary['crack']['type_list'] = original_list[:egg_count]
            print(f"Only cracking {egg_count} egg(s)."); 
    loop_count = 0
    while True:
        if allow_keyboard_input:
            key = getch(0.1)
            if key:
                break
        else:
            for key, value in action_dictionary.items():
                if value['count'] <= 0:
                    # Done all of this action, do the next
                    value['index'] += 1
                    if key == 'lean':
                        # Have a rest between leaning actions
                        print("Having a rest after leaning.")
                        command_list = motion_dictionary['centre_body']
                        for command in command_list:
                            do_command(servo_dictionary, command[0], command[1], command[2:])
                    if key == 'rotate':
                        # Look forward relatively frequently to stop staring
                        print("Looking straight ahead after rotating.")
                        command_list = motion_dictionary['centre_head']
                        for command in command_list:
                            do_command(servo_dictionary, command[0], command[1], command[2:])
                    if value['index'] >= len(value['type_list']):
                        # Done all action types, shuffle the list and reset the action index to the start
                        shuffle(value['type_list'])
                        value['index'] = 0
                        if key == 'crack':
                            if loop_count % 10 == 0:
                                # For cracks we only do the last entry in the shuffled list,
                                # and then only every 10 times around the loop, just so as
                                # not to crack too often
                                value['count'] = 1
                                value['index'] = len(value['type_list']) - 1
                        else:
                            value['count'] = randrange(value['rand_min'], value['rand_max'], value['rand_range'] )
                            if value['type_list'][value['index']]:
                                print(f"On {key}, doing {value['type_list'][value['index']]} {value['count']} time(s).")
                            else:
                                print(f"On {key}, doing nothing {value['count']} time(s).")
                if value['count'] > 0:
                    if value['type_list'][value['index']]:
                        # Do the action
                        command_list = motion_dictionary[value['type_list'][value['index']]]
                        for command in command_list:
                            do_command(servo_dictionary, command[0], command[1], command[2:])
                    else:
                        sleep(SLEEP_ANGLE_SET_SECONDS)
                    value['count'] -= 1
        loop_count += 1
    print("Back to normal key-presses now")
    return key

# Clean-up: after this the servos are set to reset positions and pi is stopped
def cleanup(pi, servo_dictionary):
    print ("Cleaning up...")
    if servo_dictionary:
        for key, servo in servo_dictionary.items():
            servo.SetAngleDegrees(0)
            servo.Stop()
    if pi and pi.connected:
        pi.stop()

def main(random_mode=False, random_mode_egg_count=0):
    # Connect to pipgiod
    pi = pigpio.pi()

    if pi.connected:
        # The servo dictionary
        servo_dictionary = {'right': Servo(pi, 17, "right", 89, -89),
                            'left': Servo(pi, 18, "left", 89, -89),
                            'head': Servo (pi, 27, "head", 10, -40),
                            'crack_0': Servo (pi, 22, "crack 0", 7, -7),
                            'crack_1': Servo (pi, 23, "crack 1", 7, -7),
                            'crack_2': Servo (pi, 24, "crack 2", 7, -7)}
        # A dictionary of motions, each with a list of commands to do to achieve that motion
        # Each thing to do starts with the servo key, then the command type and finally the parameters for that command,
        # aside from the random motion, which goes off piste
        motion_dictionary = {'forwards':     [('left',    COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES),  ('right', COMMAND_ANGLE_INCREMENT,  ANGLE_STEP_DEGREES)],
                             'backwards':    [('left',    COMMAND_ANGLE_INCREMENT,  ANGLE_STEP_DEGREES),  ('right', COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES)],
                             'left':         [('left',    COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES),  ('right', COMMAND_ANGLE_CONVERGE, 0, ANGLE_STEP_DEGREES)],
                             'right':        [('right',   COMMAND_ANGLE_INCREMENT,  ANGLE_STEP_DEGREES),  ('left',  COMMAND_ANGLE_CONVERGE, 0, ANGLE_STEP_DEGREES)],
                             'rotate_left':  [('head',    COMMAND_ANGLE_INCREMENT,  ANGLE_STEP_DEGREES)],
                             'rotate_right': [('head',    COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES)],
                             'centre':       [('left',    COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS), ('right', COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS), ('head', COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS)],
                             'centre_body':  [('left',    COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS), ('right', COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS)],
                             'centre_head':  [('head',    COMMAND_ANGLE_SET, 0, SLEEP_ANGLE_SET_SECONDS)],
                             'crack_0':      [('crack_0', COMMAND_JIGGLE,         CRACK_EGG_ANGLE_DEGREES)],
                             'crack_1':      [('crack_1', COMMAND_JIGGLE,         CRACK_EGG_ANGLE_DEGREES)],
                             'crack_2':      [('crack_2', COMMAND_JIGGLE,         CRACK_EGG_ANGLE_DEGREES)],
                             'random':       None}
        # A dictionary of actions to take for a given key press
        # Note: the arrow keys get mapped to 'A'/'B' for up/down, 'C'/'D' for right/left
        action_dictionary = {'A': 'forwards', 'B': 'backwards', 'C': 'right',   'D': 'left', 'z': 'rotate_left', 'x': 'rotate_right', 'c': 'centre',
                             '0': 'crack_0',  '1': 'crack_1',   '2': 'crack_2', 'r': 'random'}

        try:
            # Start all of the servos
            for key, servo in servo_dictionary.items():
                servo.Start()
            if random_mode:
                print("Running in random mode, CTRL-C to exit.")
                random_actions(False, servo_dictionary, motion_dictionary, random_mode_egg_count)
            else:
                # Wait for keyboard input
                print("Press z, x or the arrow keys to move the hen servos, c to centre, , 0 to 2 to crack an egg, r for random(ish), CTRL-C to exit.")
                key = None
                while True:
                    if key is None:
                         key = getch()
                    if key:
                        action = action_dictionary.get(key)
                        key = None
                        if action:
                            command_list = motion_dictionary[action]
                            if command_list:
                                for command in command_list:
                                    do_command(servo_dictionary, command[0], command[1], command[2:])
                            else:
                                # Must be random
                                key = random_actions(True, servo_dictionary, random_mode_egg_count, motion_dictionary)
                        else:
                            print("Only CTRL-C, z, x, c, r, 0 to 2, or the arrow keys up, down, left, right are valid.")
                cleanup(pi, servo_dicionary)
        except KeyboardInterrupt as ex:
            cleanup(pi, servo_dictionary)

    else:
        print("pigpiod is not running: sudo pigpiod please!")
    
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=("A script to drive the mother hen, from the keyboard or just randomly."),
                                     formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-r', action='store_true', help=("run in random (automatic) mode, no keyboard control."))
    parser.add_argument('-e', type=int, default=-1, help=("the number of eggs to include, default all."))

    args = parser.parse_args()

    main(args.r, args.e)

