|
| 1 | +# Copyright (c) FIRST and other WPILib contributors. |
| 2 | +# Open Source Software; you can modify and/or share it under the terms of |
| 3 | +# the WPILib BSD license file in the root directory of this project. |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from typing import Any, Callable |
| 7 | + |
| 8 | +from .command import Command |
| 9 | +from .subsystem import Subsystem |
| 10 | + |
| 11 | +from wpimath.controller import PIDController |
| 12 | + |
| 13 | + |
| 14 | +class PIDCommand(Command): |
| 15 | + """ |
| 16 | + A command that controls an output with a PIDController. Runs forever by default - to add |
| 17 | + exit conditions and/or other behavior, subclass this class. The controller calculation and output |
| 18 | + are performed synchronously in the command's execute() method. |
| 19 | +
|
| 20 | + This class is provided by the NewCommands VendorDep |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + controller: PIDController, |
| 26 | + measurementSource: Callable[[], float], |
| 27 | + setpoint: float, |
| 28 | + useOutput: Callable[[float], Any], |
| 29 | + *requirements: Subsystem, |
| 30 | + ): |
| 31 | + """ |
| 32 | + Creates a new PIDCommand, which controls the given output with a PIDController. |
| 33 | +
|
| 34 | + :param controller: the controller that controls the output. |
| 35 | + :param measurementSource: the measurement of the process variable |
| 36 | + :param setpoint: the controller's setpoint |
| 37 | + :param useOutput: the controller's output |
| 38 | + :param requirements: the subsystems required by this command |
| 39 | + """ |
| 40 | + super().__init__() |
| 41 | + if controller is None: |
| 42 | + raise ValueError("controller must not be None") |
| 43 | + if measurementSource is None: |
| 44 | + raise ValueError("measurementSource must not be None") |
| 45 | + if setpoint is None: |
| 46 | + raise ValueError("setpointSource must not be None") |
| 47 | + if useOutput is None: |
| 48 | + raise ValueError("useOutput must not be None") |
| 49 | + |
| 50 | + self.controller = controller |
| 51 | + self.useOutput = useOutput |
| 52 | + self.measurement = measurementSource |
| 53 | + self.setpoint = setpoint |
| 54 | + self.requirements.addAll(set(requirements)) |
| 55 | + |
| 56 | + def initialize(self): |
| 57 | + self.controller.reset() |
| 58 | + |
| 59 | + def execute(self): |
| 60 | + self.useOutput(self.controller.calculate(self.measurement(), self.setpoint)) |
| 61 | + |
| 62 | + def end(self, interrupted): |
| 63 | + self.useOutput(0) |
| 64 | + |
| 65 | + def getController(self): |
| 66 | + """ |
| 67 | + Returns the PIDController used by the command. |
| 68 | +
|
| 69 | + :return: The PIDController |
| 70 | + """ |
| 71 | + return self.controller |
0 commit comments