Python Library State Machine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

example.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. import sys
  4. sys.path.append('../..')
  5. import logging
  6. import os
  7. import report
  8. import state_machine
  9. logger = logging.getLogger('root')
  10. report.stdoutLoggingConfigure(log_name_lvl=[('root', 'DEBUG'), ])
  11. class trafic_lights(state_machine.state_machine):
  12. LOG_PREFIX = 'TraficLights:'
  13. STATE_RED = 'state_red'
  14. STATE_GREEN = 'state_green'
  15. CONDITION_TRUE = 'condition_true'
  16. CONDITION_PEDASTRIAN_REQUEST = 'condition_pedastrian_request'
  17. TRANSITIONS = {
  18. STATE_RED: (
  19. (CONDITION_PEDASTRIAN_REQUEST, 1, STATE_GREEN),
  20. ),
  21. STATE_GREEN: (
  22. (CONDITION_TRUE, 3, STATE_RED),
  23. )
  24. }
  25. def condition_true(self):
  26. return True
  27. def set_padestrian_request(self):
  28. logger.log(self.__log_lvl__, '%s Pedestrian gave state change request.', self.LOG_PREFIX)
  29. self.pedastrian_request = True
  30. def condition_pedastrian_request(self):
  31. return self.pedastrian_request
  32. sm = trafic_lights(trafic_lights.STATE_RED, logging.INFO, pedastrian_request=False)
  33. sm.register_state_change_callback(sm.STATE_GREEN, sm.CONDITION_PEDASTRIAN_REQUEST, logger.info, 'Callback information: Traffic light had been changed to green caused by pedastrian request')
  34. while not sm.previous_state_was(sm.STATE_GREEN):
  35. if sm.this_state_is(sm.STATE_RED) and sm.this_state_duration() > 0.2 and not sm.condition_pedastrian_request():
  36. sm.set_padestrian_request()
  37. sm.work()