"""Simple speed controller.
The *speed_controller* module contains the `SpeedController` class.
`SpeedController` was made into a class for two reasons:
1) So it would be easier to have more than one SpeedController,
each with their own tuning parameter(s).
2) The current controller is the simplest there is, and there are
a lot of fancier (more tweakable) controllers that we might create
in the future. By wrapping this code up in a class now, it will be
easier to swap in fancier controllers (PI, PD, PID) in the future.
"""
[docs]class SpeedController:
    """A minimal speed controller that implements Proportional control.
    When you create one of these, you provide it a constant of proportionality.
    For example, 0.5 would correspond to 50%.
    """
    def __init__(self, kP):
        self.kP = kP
[docs]    def compute_power(self, target_speed, measured_speed, motor_power, min_motor_power, max_motor_power):
        """Based on desired versus actual motor speed, compute a new power level that should help.
        Args:
            target_speed (number): The speed you want.
            measured_speed (number): The speed you are currently at.
            motor_power (int): The motor power you are currently applying.
            min_motor_power (int): The minimum motor power you want to apply.
            max_motor_power (int): The maximum motor power you want to apply.
        Returns:
            (int): a power level as good or better than the one you had before.
        """
        error = target_speed - measured_speed
        correction = error * self.kP
        motor_power += correction
        # Keep within specified limits
        if motor_power < min_motor_power:
            motor_power = min_motor_power
        if motor_power > max_motor_power:
            motor_power = max_motor_power
        return motor_power