title: State machine and toggling states in a loop
body: <p>I've got an application running on a BeagleBone Black controlling some hardware. The user interface consists of an LCD display and a rotary encoder switch with an integrated push button.</p>
  
  <p>In terms of state transitions, all what the application does is to react to push button events to switch between them:</p>
  
  <ul>
  <li>Initial state: "manual"</li>
  <li>Push event: toggle state to next ("auto"), do auto actions</li>
  <li>Push event: toggle state to next ("manual"), do manual actions</li>
  </ul>
  
  <p>In summary, there are two states, and the trigger is the button push, which actually toggles between the two.</p>
  
  <p>The current code is an infinite loop with an if ... else condition that executes either the "manual" mode or "auto" mode actions depending on the state. A delay is added at the end of the loop. The <code>manual</code> variable is updated (toggled) by an interrupt whenever a push button event is detected.</p>
  
  <pre><code>while True:
      # Toggle mode when the push button event is detected
      # It can also be detected asynchronously outside the loop,
      # but we'll keep it on the loop for a smaller example
      if gpio.event_detected(push_button):
          manual_mode = not manual_mode
  
      if manual_mode:
          # MANUAL MODE:
          do_user_input_actions()
      else:
          # AUTO mode
          do_automatic_actions()
  
     time.sleep(0.5)
  </code></pre>
  
  <p>This construct is <em>similar</em> to the <a href="https://stackoverflow.com/a/1648098/9022675">C equivalent</a> that I've used a few times before. But I was wondering of a more object-oriented way of doing the same in Python.</p>
  
  <p>Essentially, it seems that the logic would lend itself to using <a href="https://github.com/pytransitions" rel="nofollow noreferrer">pytransitions</a>, particularly if I need to add more states in the future, so I'm considering porting the code to it.</p>
  
  <p>I can picture the two states and the transitions:</p>
  
  <pre><code>states = ['manual', 'sweep']
  transitions = [['handle_manual_input', 'auto', 'manual'],
                 ['run_auto_test', 'manual', 'auto']]
  </code></pre>
  
  <p>However, I can't quite visualize what the proper way to implement the equivalent of my current infinite loop with the state check is in the <em>pytranslations</em> model.</p>
  
  <p>Effectively, handling manual input should be done on each loop iteration, and not just on the transition from auto, and vice versa for running the auto mode.</p>
  
  <p>I understand that the state machine should be left alone to just take care of the states and transitions for better code separation.</p>
  
  <p>It's the model implementation that I can't quite picture: I'd welcome any guidance on how and where to run <code>do_user_input_actions()</code> and <code>do_automatic_actions()</code>.</p>