Is there a way in MagicBot to simply implement a 'whenPressed' action?

Howdy!

Our team has been using RobotPy for already 2 years with the MagicBot framework, and we’ve always questioned the way we currently implemented pressed actions - i.e actions that happen only once when a joystick button is pressed.

Due to the fact that both components and the robot itself run in a loop, we have to check whether the joystick state was changed from the previous iteration, and so we use a boolean variable for every action. The code gets a bit messy, and it seems like it can be implemented a lot better.

Currently, the structure of such an action inside teleopPeriodic looks similar to:

if button.get() and not self.did_action:
    self.component.do_action()
    self.did_action = True
else:
    self.did_action = False

From our perspective, it looks weird that the handling of button states is done in the robot class, especially not creating a boolean variable for every such action. It is possible to do the same thing inside the specific component creating 2 functions like:

def do_action(self):
    if not self.did_action:
        self.action_flag = self.did_action = True

def reset_action(self):
   self.did_action = False

And then in teleopPeriodic:

if button.get():
    self.component.do_action()
else:
    self.component.reset_action()

Both ways seem pretty messy and require creating functions and variables for each and every such action - which is bad practice and creates a ton load of code repetition which cannot be generalized because the components are not related to each other. Have any of you or your team found a better solution to this problem, or perhaps something can be done within the library to make such actions easier?

Thanks in advance,
~ Nick S. - Phoenix 5654

Each button getter on HID objects (such as getRawButton, Joystick.getTrigger, and XboxController.getAButton) have corresponding getButtonPressed and getButtonReleased methods.

Ok, good to know! So as oppsed to using wpilib.buttons.JoystickButton, creating buttons inside the createObjects function and then checking their condition - we should simply check the condition of self.joystick.getRawButtonPressed(button) (with self.joystick being our josytick object) for the conditional of the action for example, right?

Yeah. Don’t use wpilib.buttons unless you’re actually using the command framework.

Okay, sweet! Yeah, we were confused a bit with wpilib.buttons since we used it back when we used the command framework, and never noticed these were intended only for it, so we continued using it after the switch to MagicBot - but now we know. Thanks a lot :slight_smile:

While David’s advice is correct, you’re right that button pressing handling is a glaring omission from Magicbot. I’ve never really found a good pythonic magicboty way to deal with it yet. Feel free to offer suggestions!

1 Like