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.
In terms of state transitions, all what the application does is to react to push button events to switch between them:
- Initial state: "manual"
- Push event: toggle state to next ("auto"), do auto actions
- Push event: toggle state to next ("manual"), do manual actions
In summary, there are two states, and the trigger is the button push, which actually toggles between the two.
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 manual
variable is updated (toggled) by an interrupt whenever a push button event is detected.
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)
This construct is similar to the C equivalent that I've used a few times before. But I was wondering of a more object-oriented way of doing the same in Python.
Essentially, it seems that the logic would lend itself to using pytransitions, particularly if I need to add more states in the future, so I'm considering porting the code to it.
I can picture the two states and the transitions:
states = ['manual', 'sweep']
transitions = [['handle_manual_input', 'auto', 'manual'],
['run_auto_test', 'manual', 'auto']]
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 pytranslations model.
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.
I understand that the state machine should be left alone to just take care of the states and transitions for better code separation.
It's the model implementation that I can't quite picture: I'd welcome any guidance on how and where to run do_user_input_actions()
and do_automatic_actions()
.