9 from caf.state_machines
import Machine, State
16 def print_msg_before(**kwargs):
18 Callbacks on transitions have access to keyword arguments that you can
19 specify when calling a transition. But remember that all kwargs are passed
20 to ALL transition callbacks. Including both the before and after callbacks
22 b2.B2INFO(kwargs[
"msg_before"])
25 def print_msg_after(**kwargs):
27 Have to have a different kwarg name, otherwise the same argument from the
28 'before' callback will be used
30 b2.B2INFO(kwargs[
"msg_after"])
33 def enter_new_state(**kwargs):
35 Enter and exit callbacks have access to the prior and new state objects but NOT
36 the transition arguments.
38 b2.B2INFO(
"Entering state {} from state {}".format(kwargs[
"new_state"].name, kwargs[
"prior_state"].name))
41 def exit_old_state(**kwargs):
42 b2.B2INFO(
"Exiting state {} to state {}".format(kwargs[
"prior_state"].name, kwargs[
"new_state"].name))
45 def condition_true(**kwargs):
46 b2.B2INFO(
"Evaluating conditions")
52 m1.add_state(State(
"start", enter=enter_new_state, exit=exit_old_state))
53 m1.add_state(
"running", enter=enter_new_state, exit=exit_old_state)
54 m1.add_state(
"end", enter=enter_new_state, exit=exit_old_state)
56 m1.add_transition(trigger=
"begin", source=
"start", dest=
"running",
57 conditions=condition_true, before=print_msg_before, after=print_msg_after)
58 m1.add_transition(
"finish",
"running",
"end",
59 conditions=condition_true, before=print_msg_before, after=print_msg_after)
62 m1.initial_state =
"start"
66 m1.save_graph(filename=
"machine_graph.dot", graphname=
"Machine")
69 b2.B2INFO(
"Currently in " + m1.state.name +
" state.")
70 m1.begin(msg_before=
"About to run", msg_after=
"Now Running")
71 m1.finish(msg_before=
"Finishing", msg_after=
"Finished")
72 b2.B2INFO(
"Currently in " + m1.state.name +
" state.")