Trigger transition on button press from xbox controller #670
Replies: 1 comment
-
Hello @sankethm22, the trigger function is defined by the transitions passed to a machine. A trigger must be executed for a transition to happen. All transition function are defined on the state model. If you don't pass a model parameter to If you want a transition happening under certain conditions, you can use the from transitions import Machine
from time import sleep
from dataclasses import dataclass
import random
@dataclass
class ControllerState:
up: bool = False
down: bool = False
left: bool = False
right: bool = False
def get_state() -> ControllerState:
return ControllerState(up=random.choice([True, False])) # will randomly return an up state
def is_xbox_up(xbox_state) -> bool:
return xbox_state.up
transitions = [{'trigger': 'poll', 'source': 'here', 'dest': 'there', 'conditions': is_xbox_up}]
machine = Machine(states=['here', 'there'], transitions=transitions, initial='here')
assert machine.is_here()
print(f"Current state: {machine.state}")
print("Polling button state...")
while not machine.poll(get_state()):
print("Button was not up. Sleeping...")
# try to transition, will return True if successful (condition is met) and False otherwise
# Polling too often causes higher load and polling too rarely may cause lag
sleep(0.01)
print("Polling button state again...")
assert machine.is_there()
print(f"Current state: {machine.state}") As you see, we can pass an argument to the function that checks a certain condition. Note that if you pass an argument to a trigger, ALL callbacks have to be able to process that parameter (see the Readme about callbacks for further details). Also note that we also stopped polling after ONE successful condition check. You could of course poll the button state again but you might want to add a certain delay because otherwise state transitions may happen too fast. If the code you use to read out button states allows event-based communication you can skip polling and condition checks and call a trigger directly instead: transitions = [{'trigger': 'button_up', 'source': 'here', 'dest': 'there'}]
machine = Machine(states=['here', 'there'], transitions=transitions, initial='here')
def on_button_up():
assert machine.button_up() # this will return True because there is currently nothing that could prevent a successful transition |
Beta Was this translation helpful? Give feedback.
-
Hello,
I was wondering how we can trigger a transition when a button is pressed on xbox controller.
Currently, I can get the xbox state for button and I want to trigger if state of a button is True. I am assuming I can define the trigger function. But does the transition happen if the trigger function return True?
For ex:
Note: I have the xbox state updating in a loop
Beta Was this translation helpful? Give feedback.
All reactions