pgularski / pysm

Versatile and flexible Python State Machine library
http://pysm.readthedocs.io/
MIT License
73 stars 11 forks source link

Get the availiable states from a given state #2

Closed Annakan closed 5 years ago

Annakan commented 7 years ago

Hello, Pysm seems to be the "most advanced and versatile" FSM python package but I am looking for a method to get the available transitions from a state. Did I miss something ? or is there a way to build that without side effects ?

It is very very useful to be able to connect it to a graphical interface without duplication of the states in the GUI. Available buttons and commands should be mapped/mappable to "current_subject_object.currentState.getPossibleNextStates()"

Thanks a lot for your time.

pgularski commented 7 years ago

Hi,

Currently there's no such functionality to get a list of next possible states. The quick and dirty solution to this would be something like below. You can adapt it to your own needs. Remember that even if there's a transition listed in the next_states it might be prevented by a condition callback.

def get_next_states(state):
    next_states = []
    # Machine has transitions, not a state
    machine = state.parent
    while machine:
        machine_transitions = machine._transitions._transitions
        transition_keys = [t for t in machine_transitions.keys() if t[0] is state]

        for key in transition_keys:
            if machine_transitions[key]:
                for transition in machine_transitions[key]:
                    to_state = transition["to_state"]
                    if to_state is None:
                        # It's a transition to the same state
                        to_state = state
                    next_states.append(to_state)
        machine = machine.parent

    return next_states
pgularski commented 5 years ago

Since I didn't hear from @Annakan anymore I close this issue.