|
| 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, Union |
| 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 | + |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + controller: PIDController, |
| 24 | + measurementSource: Callable[[], float], |
| 25 | + setpoint: Union[Callable[[], float], float, int], |
| 26 | + useOutput: Callable[[float], Any], |
| 27 | + *requirements: Subsystem, |
| 28 | + ): |
| 29 | + """ |
| 30 | + Creates a new PIDCommand, which controls the given output with a PIDController. |
| 31 | +
|
| 32 | + :param controller: the controller that controls the output. |
| 33 | + :param measurementSource: the measurement of the process variable |
| 34 | + :param setpoint: the controller's setpoint (either a function that returns a) |
| 35 | + number or a number |
| 36 | + :param useOutput: the controller's output |
| 37 | + :param requirements: the subsystems required by this command |
| 38 | + """ |
| 39 | + super().__init__() |
| 40 | + |
| 41 | + self._controller = controller |
| 42 | + self._useOutput = useOutput |
| 43 | + self._measurement = measurementSource |
| 44 | + |
| 45 | + if isinstance(setpoint, (float, int)): |
| 46 | + setpoint = float(setpoint) |
| 47 | + self._setpoint = lambda: setpoint |
| 48 | + elif callable(setpoint): |
| 49 | + self._setpoint = setpoint |
| 50 | + else: |
| 51 | + raise ValueError( |
| 52 | + f"invalid setpoint (must be callable or number; got {type(setpoint)})" |
| 53 | + ) |
| 54 | + |
| 55 | + self.addRequirements(*requirements) |
| 56 | + |
| 57 | + def initialize(self): |
| 58 | + self._controller.reset() |
| 59 | + |
| 60 | + def execute(self): |
| 61 | + self._useOutput( |
| 62 | + self._controller.calculate(self._measurement(), self._setpoint()) |
| 63 | + ) |
| 64 | + |
| 65 | + def end(self, interrupted): |
| 66 | + self._useOutput(0) |
| 67 | + |
| 68 | + def getController(self): |
| 69 | + """ |
| 70 | + Returns the PIDController used by the command. |
| 71 | +
|
| 72 | + :return: The PIDController |
| 73 | + """ |
| 74 | + return self._controller |
0 commit comments