From 2bd816297527e77fb44a03ddf4aca35124f6f303 Mon Sep 17 00:00:00 2001 From: Dirk Alders Date: Sun, 3 Jan 2021 21:17:15 +0100 Subject: [PATCH] Module documentation update --- __init__.py | 4 ++-- _examples_/Makefile | 11 ++++++++++ _examples_/example.py | 50 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 _examples_/Makefile create mode 100644 _examples_/example.py diff --git a/__init__.py b/__init__.py index 2c7c4bc..072dc67 100644 --- a/__init__.py +++ b/__init__.py @@ -61,9 +61,9 @@ class state_machine(object): **Example:** - .. literalinclude:: ../examples/example.py + .. literalinclude:: state_machine/_examples_/example.py - .. literalinclude:: ../examples/example.log + .. literalinclude:: state_machine/_examples_/example.log """ TRANSITIONS = {} LOG_PREFIX = 'StateMachine:' diff --git a/_examples_/Makefile b/_examples_/Makefile new file mode 100644 index 0000000..26c3d88 --- /dev/null +++ b/_examples_/Makefile @@ -0,0 +1,11 @@ +EXAMPLES = $(wildcard *.py) +LOGFILES = ${EXAMPLES:.py=.log} + +.PHONY: all +all: $(LOGFILES) + +%.log: %.py + python3 $< > $@ + +clean: + rm $(LOGFILES) diff --git a/_examples_/example.py b/_examples_/example.py new file mode 100644 index 0000000..2886380 --- /dev/null +++ b/_examples_/example.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +import sys +sys.path.append('../..') +import logging +import os + +import report +import state_machine + +logger = logging.getLogger('root') +report.stdoutLoggingConfigure(log_name_lvl=[('root', 'DEBUG'), ]) + + +class trafic_lights(state_machine.state_machine): + LOG_PREFIX = 'TraficLights:' + + STATE_RED = 'state_red' + STATE_GREEN = 'state_green' + + CONDITION_TRUE = 'condition_true' + CONDITION_PEDASTRIAN_REQUEST = 'condition_pedastrian_request' + + TRANSITIONS = { + STATE_RED: ( + (CONDITION_PEDASTRIAN_REQUEST, 1, STATE_GREEN), + ), + STATE_GREEN: ( + (CONDITION_TRUE, 3, STATE_RED), + ) + } + + def condition_true(self): + return True + + def set_padestrian_request(self): + logger.log(self.__log_lvl__, '%s Pedestrian gave state change request.', self.LOG_PREFIX) + self.pedastrian_request = True + + def condition_pedastrian_request(self): + return self.pedastrian_request + + +sm = trafic_lights(trafic_lights.STATE_RED, logging.INFO, pedastrian_request=False) +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') +while not sm.previous_state_was(sm.STATE_GREEN): + if sm.this_state_is(sm.STATE_RED) and sm.this_state_duration() > 0.2 and not sm.condition_pedastrian_request(): + sm.set_padestrian_request() + sm.work()