Skip to content

Added PIDCommand.py using ChatGPT translator #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 5, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions commands2/pidcommand.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright (c) FIRST and other WPILib contributors.
# Open Source Software; you can modify and/or share it under the terms of
# the WPILib BSD license file in the root directory of this project.
from __future__ import annotations

from typing import Any, Callable, Union

from .command import Command
from .subsystem import Subsystem

from wpimath.controller import PIDController


class PIDCommand(Command):
"""
A command that controls an output with a PIDController. Runs forever by default - to add
exit conditions and/or other behavior, subclass this class. The controller calculation and output
are performed synchronously in the command's execute() method.
"""

def __init__(
self,
controller: PIDController,
measurementSource: Callable[[], float],
setpoint: Union[Callable[[], float], float, int],
useOutput: Callable[[float], Any],
*requirements: Subsystem,
):
"""
Creates a new PIDCommand, which controls the given output with a PIDController.

:param controller: the controller that controls the output.
:param measurementSource: the measurement of the process variable
:param setpoint: the controller's setpoint (either a function that returns a)
number or a number
:param useOutput: the controller's output
:param requirements: the subsystems required by this command
"""
super().__init__()

self._controller = controller
self._useOutput = useOutput
self._measurement = measurementSource

if isinstance(setpoint, (float, int)):
setpoint = float(setpoint)
self._setpoint = lambda: setpoint
elif callable(setpoint):
self._setpoint = setpoint
else:
raise ValueError(
f"invalid setpoint (must be callable or number; got {type(setpoint)})"
)

self.addRequirements(*requirements)

def initialize(self):
self._controller.reset()

def execute(self):
self._useOutput(
self._controller.calculate(self._measurement(), self._setpoint())
)

def end(self, interrupted):
self._useOutput(0)

def getController(self):
"""
Returns the PIDController used by the command.

:return: The PIDController
"""
return self._controller