2 from caf.state_machines
import Machine, State
9 def print_msg_before(**kwargs):
11 Callbacks on transitions have access to keyword arguments that you can
12 specify when calling a transition. But remember that all kwargs are passed
13 to ALL transition callbacks. Including both the before and after callbacks
15 b2.B2INFO(kwargs[
"msg_before"])
18 def print_msg_after(**kwargs):
20 Have to have a different kwarg name, otherwise the same argument from the
21 'before' callback will be used
23 b2.B2INFO(kwargs[
"msg_after"])
26 def enter_new_state(**kwargs):
28 Enter and exit callbacks have access to the prior and new state objects but NOT
29 the transition arguments.
31 b2.B2INFO(
"Entering state {0} from state {1}".format(kwargs[
"new_state"].name, kwargs[
"prior_state"].name))
34 def exit_old_state(**kwargs):
35 b2.B2INFO(
"Exiting state {0} to state {1}".format(kwargs[
"prior_state"].name, kwargs[
"new_state"].name))
38 def condition_true(**kwargs):
39 b2.B2INFO(
"Evaluating conditions")
45 m1.add_state(State(
"start", enter=enter_new_state, exit=exit_old_state))
46 m1.add_state(
"running", enter=enter_new_state, exit=exit_old_state)
47 m1.add_state(
"end", enter=enter_new_state, exit=exit_old_state)
49 m1.add_transition(trigger=
"begin", source=
"start", dest=
"running",
50 conditions=condition_true, before=print_msg_before, after=print_msg_after)
51 m1.add_transition(
"finish",
"running",
"end",
52 conditions=condition_true, before=print_msg_before, after=print_msg_after)
55 m1.initial_state =
"start"
59 m1.save_graph(filename=
"machine_graph.dot", graphname=
"Machine")
62 b2.B2INFO(
"Currently in " + m1.state.name +
" state.")
63 m1.begin(msg_before=
"About to run", msg_after=
"Now Running")
64 m1.finish(msg_before=
"Finishing", msg_after=
"Finished")
65 b2.B2INFO(
"Currently in " + m1.state.name +
" state.")